text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import 'chrome://resources/cr_elements/hidden_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import './print_preview_vars_css.js'; import '../strings.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {isMac} from 'chrome://resources/js/cr.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {DarkModeMixin} from '../dark_mode_mixin.js'; import {Coordinate2d} from '../data/coordinate2d.js'; import {Destination} from '../data/destination.js'; import {getPrinterTypeForDestination} from '../data/destination_match.js'; import {CustomMarginsOrientation, Margins, MarginsSetting, MarginsType} from '../data/margins.js'; import {MeasurementSystem} from '../data/measurement_system.js'; import {DuplexMode, MediaSizeValue, Ticket} from '../data/model.js'; import {PrintableArea} from '../data/printable_area.js'; import {ScalingType} from '../data/scaling.js'; import {Size} from '../data/size.js'; import {Error, State} from '../data/state.js'; import {MetricsContext, PrintPreviewInitializationEvents} from '../metrics.js'; import {NativeLayer, NativeLayerImpl} from '../native_layer.js'; import {areRangesEqual} from '../print_preview_utils.js'; import {MARGIN_KEY_MAP, MarginObject, PrintPreviewMarginControlContainerElement} from './margin_control_container.js'; import {PluginProxy, PluginProxyImpl} from './plugin_proxy.js'; import {SettingsMixin} from './settings_mixin.js'; type PreviewTicket = Ticket&{ headerFooterEnabled: boolean; pageRange: Array<{to: number, from: number}>; pagesPerSheet: number; isFirstRequest: boolean; requestID: number; } export enum PreviewAreaState { LOADING = 'loading', DISPLAY_PREVIEW = 'display-preview', OPEN_IN_PREVIEW_LOADING = 'open-in-preview-loading', OPEN_IN_PREVIEW_LOADED = 'open-in-preview-loaded', ERROR = 'error', } export interface PrintPreviewPreviewAreaElement { $: {marginControlContainer: PrintPreviewMarginControlContainerElement;}; } const PrintPreviewPreviewAreaElementBase = WebUIListenerMixin(I18nMixin(SettingsMixin(DarkModeMixin(PolymerElement)))); export class PrintPreviewPreviewAreaElement extends PrintPreviewPreviewAreaElementBase { static get is() { return 'print-preview-preview-area'; } static get template() { return html`{__html_template__}`; } static get properties() { return { destination: Object, documentModifiable: Boolean, error: { type: Number, notify: true, }, margins: Object, measurementSystem: Object, pageSize: Object, previewState: { type: String, notify: true, value: PreviewAreaState.LOADING, }, state: Number, pluginLoadComplete_: { type: Boolean, value: false, }, documentReady_: { type: Boolean, value: false, }, previewLoaded_: { type: Boolean, notify: true, computed: 'computePreviewLoaded_(documentReady_, pluginLoadComplete_)', }, }; } static get observers() { return [ 'onDarkModeChanged_(inDarkMode)', 'pluginOrDocumentStatusChanged_(pluginLoadComplete_, documentReady_)', 'onStateOrErrorChange_(state, error)', ]; } destination: Destination; documentModifiable: boolean; error: Error; margins: Margins; measurementSystem: MeasurementSystem|null; pageSize: Size; previewState: PreviewAreaState; state: State; private pluginLoadComplete_: boolean; private documentReady_: boolean; private previewLoaded_: boolean; private nativeLayer_: NativeLayer|null = null; private lastTicket_: PreviewTicket|null = null; private inFlightRequestId_: number = -1; private pluginProxy_: PluginProxy = PluginProxyImpl.getInstance(); private keyEventCallback_: ((e: KeyboardEvent) => void)|null = null; connectedCallback() { super.connectedCallback(); this.nativeLayer_ = NativeLayerImpl.getInstance(); this.addWebUIListener( 'page-preview-ready', this.onPagePreviewReady_.bind(this)); } private computePreviewLoaded_(): boolean { return this.documentReady_ && this.pluginLoadComplete_; } previewLoaded(): boolean { return this.previewLoaded_; } /** * Called when the pointer moves onto the component. Shows the margin * controls if custom margins are being used. * @param event Contains element pointer moved from. */ private onPointerOver_(event: PointerEvent) { const marginControlContainer = this.$.marginControlContainer; let fromElement = event.relatedTarget as HTMLElement | null; while (fromElement !== null) { if (fromElement === marginControlContainer) { return; } fromElement = fromElement.parentElement; } marginControlContainer.setInvisible(false); } /** * Called when the pointer moves off of the component. Hides the margin * controls if they are visible. * @param event Contains element pointer moved to. */ private onPointerOut_(event: PointerEvent) { const marginControlContainer = this.$.marginControlContainer; let toElement = event.relatedTarget as HTMLElement | null; while (toElement !== null) { if (toElement === marginControlContainer) { return; } toElement = toElement.parentElement; } marginControlContainer.setInvisible(true); } private pluginOrDocumentStatusChanged_() { if (!this.pluginLoadComplete_ || !this.documentReady_ || this.previewState === PreviewAreaState.ERROR) { return; } this.previewState = this.previewState === PreviewAreaState.OPEN_IN_PREVIEW_LOADING ? PreviewAreaState.OPEN_IN_PREVIEW_LOADED : PreviewAreaState.DISPLAY_PREVIEW; } /** * @return 'invisible' if overlay is invisible, '' otherwise. */ private getInvisible_(): string { return this.isInDisplayPreviewState_() ? 'invisible' : ''; } /** * @return 'true' if overlay is aria-hidden, 'false' otherwise. */ private getAriaHidden_(): string { return this.isInDisplayPreviewState_().toString(); } /** * @return Whether the preview area is in DISPLAY_PREVIEW state. */ private isInDisplayPreviewState_(): boolean { return this.previewState === PreviewAreaState.DISPLAY_PREVIEW; } /** * @return Whether the preview is currently loading. */ private isPreviewLoading_(): boolean { return this.previewState === PreviewAreaState.LOADING; } /** * @return 'jumping-dots' to enable animation, '' otherwise. */ private getJumpingDots_(): string { return this.isPreviewLoading_() ? 'jumping-dots' : ''; } /** * @return Whether the "learn more" link to the cloud print help * page should be shown. */ private shouldShowLearnMoreLink_(): boolean { return this.error === Error.UNSUPPORTED_PRINTER; } /** * @return The current preview area message to display. */ private currentMessage_(): string { switch (this.previewState) { case PreviewAreaState.LOADING: return this.i18n('loading'); case PreviewAreaState.DISPLAY_PREVIEW: return ''; // <if expr="is_macosx"> case PreviewAreaState.OPEN_IN_PREVIEW_LOADING: case PreviewAreaState.OPEN_IN_PREVIEW_LOADED: return this.i18n('openingPDFInPreview'); // </if> case PreviewAreaState.ERROR: // The preview area is responsible for displaying all errors except // print failed and cloud print error. return this.getErrorMessage_(); default: return ''; } } /** * @param forceUpdate Whether to force the preview area to update * regardless of whether the print ticket has changed. */ startPreview(forceUpdate: boolean) { if (!this.hasTicketChanged_() && !forceUpdate && this.previewState !== PreviewAreaState.ERROR) { return; } this.previewState = PreviewAreaState.LOADING; this.documentReady_ = false; this.getPreview_().then( previewUid => { MetricsContext.getPreview().record( PrintPreviewInitializationEvents.FUNCTION_SUCCESSFUL); if (!this.documentModifiable) { this.onPreviewStart_(previewUid, -1); } this.documentReady_ = true; }, type => { MetricsContext.getPreview().record( PrintPreviewInitializationEvents.FUNCTION_FAILED); if (type === 'SETTINGS_INVALID') { this.error = Error.INVALID_PRINTER; this.previewState = PreviewAreaState.ERROR; } else if (type !== 'CANCELLED') { this.error = Error.PREVIEW_FAILED; this.previewState = PreviewAreaState.ERROR; } }); MetricsContext.getPreview().record( PrintPreviewInitializationEvents.FUNCTION_INITIATED); } // <if expr="is_macosx"> /** Set the preview state to display the "opening in preview" message. */ setOpeningPdfInPreview() { assert(isMac); this.previewState = this.previewState === PreviewAreaState.LOADING ? PreviewAreaState.OPEN_IN_PREVIEW_LOADING : PreviewAreaState.OPEN_IN_PREVIEW_LOADED; } // </if> /** * @param previewUid The unique identifier of the preview. * @param index The index of the page to preview. */ private onPreviewStart_(previewUid: number, index: number) { if (!this.pluginProxy_.pluginReady()) { const plugin = this.pluginProxy_.createPlugin(previewUid, index); this.pluginProxy_.setKeyEventCallback(this.keyEventCallback_!); this.shadowRoot!.querySelector( '.preview-area-plugin-wrapper')!.appendChild(plugin); this.pluginProxy_.setLoadCompleteCallback( this.onPluginLoadComplete_.bind(this)); this.pluginProxy_.setViewportChangedCallback( this.onPreviewVisualStateChange_.bind(this)); } this.pluginLoadComplete_ = false; if (this.inDarkMode) { this.pluginProxy_.darkModeChanged(true); } this.pluginProxy_.resetPrintPreviewMode( previewUid, index, !this.getSettingValue('color'), (this.getSettingValue('pages') as number[]), this.documentModifiable); } /** * Called when the plugin loads the preview completely. * @param success Whether the plugin load succeeded or not. */ private onPluginLoadComplete_(success: boolean) { if (success) { this.pluginLoadComplete_ = true; } else { this.error = Error.PREVIEW_FAILED; this.previewState = PreviewAreaState.ERROR; } } /** * Called when the preview plugin's visual state has changed. This is a * consequence of scrolling or zooming the plugin. Updates the custom * margins component if shown. * @param pageX The horizontal offset for the page corner in pixels. * @param pageY The vertical offset for the page corner in pixels. * @param pageWidth The page width in pixels. * @param viewportWidth The viewport width in pixels. * @param viewportHeight The viewport height in pixels. */ private onPreviewVisualStateChange_( pageX: number, pageY: number, pageWidth: number, viewportWidth: number, viewportHeight: number) { // Ensure the PDF viewer isn't tabbable if the window is small enough that // the zoom toolbar isn't displayed. const tabindex = viewportWidth < 300 || viewportHeight < 200 ? '-1' : '0'; this.shadowRoot!.querySelector('.preview-area-plugin')!.setAttribute( 'tabindex', tabindex); this.$.marginControlContainer.updateTranslationTransform( new Coordinate2d(pageX, pageY)); this.$.marginControlContainer.updateScaleTransform( pageWidth / this.pageSize.width); this.$.marginControlContainer.updateClippingMask( new Size(viewportWidth, viewportHeight)); // Align the margin control container with the preview content area. // The offset may be caused by the scrollbar on the left in the preview // area in right-to-left direction. const previewDocument = this.shadowRoot! .querySelector<HTMLIFrameElement>( '.preview-area-plugin')!.contentDocument; if (previewDocument && previewDocument.documentElement) { this.$.marginControlContainer.style.left = previewDocument.documentElement.offsetLeft + 'px'; } } /** * Called when a page's preview has been generated. * @param pageIndex The index of the page whose preview is ready. * @param previewUid The unique ID of the print preview UI. * @param previewResponseId The preview request ID that this page * preview is a response to. */ private onPagePreviewReady_( pageIndex: number, previewUid: number, previewResponseId: number) { if (this.inFlightRequestId_ !== previewResponseId) { return; } const pageNumber = pageIndex + 1; let index = this.getSettingValue('pages').indexOf(pageNumber); // When pagesPerSheet > 1, the backend will always return page indices 0 to // N-1, where N is the total page count of the N-upped document. const pagesPerSheet = (this.getSettingValue('pagesPerSheet') as number); if (pagesPerSheet > 1) { index = pageIndex; } if (index === 0) { this.onPreviewStart_(previewUid, pageIndex); } if (index !== -1) { this.pluginProxy_.loadPreviewPage(previewUid, pageIndex, index); } } private onDarkModeChanged_() { if (this.pluginProxy_.pluginReady()) { this.pluginProxy_.darkModeChanged(this.inDarkMode); } if (this.previewState === PreviewAreaState.DISPLAY_PREVIEW) { this.startPreview(true); } } /** * Processes a keyboard event that could possibly be used to change state of * the preview plugin. * @param e Keyboard event to process. */ handleDirectionalKeyEvent(e: KeyboardEvent) { // Make sure the PDF plugin is there. // We only care about: PageUp, PageDown, Left, Up, Right, Down. // If the user is holding a modifier key, ignore. if (!this.pluginProxy_.pluginReady() || !['PageUp', 'PageDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'] .includes(e.code) || hasKeyModifiers(e)) { return; } // Don't handle the key event for these elements. const tagName = (e.composedPath()[0] as HTMLElement).tagName; if (['INPUT', 'SELECT', 'EMBED'].includes(tagName)) { return; } // For the most part, if any div of header was the last clicked element, // then the active element is the body. Starting with the last clicked // element, and work up the DOM tree to see if any element has a // scrollbar. If there exists a scrollbar, do not handle the key event // here. const isEventHorizontal = ['ArrowLeft', 'ArrowRight'].includes(e.code); for (let i = 0; i < e.composedPath().length; i++) { const element = e.composedPath()[i] as HTMLElement; if (element.scrollHeight > element.clientHeight && !isEventHorizontal || element.scrollWidth > element.clientWidth && isEventHorizontal) { return; } } // No scroll bar anywhere, or the active element is something else, like a // button. Note: buttons have a bigger scrollHeight than clientHeight. this.pluginProxy_.sendKeyEvent(e); e.preventDefault(); } /** * Sends a message to the plugin to hide the toolbars after a delay. */ hideToolbar() { if (!this.pluginProxy_.pluginReady()) { return; } this.pluginProxy_.hideToolbar(); } /** * Set a callback that gets called when a key event is received that * originates in the plugin. * @param callback The callback to be called with a key event. */ setPluginKeyEventCallback(callback: (e: KeyboardEvent) => void) { this.keyEventCallback_ = callback; } /** * Called when dragging margins starts or stops. */ private onMarginDragChanged_(e: CustomEvent<boolean>) { if (!this.pluginProxy_.pluginReady()) { return; } // When hovering over the plugin (which may be in a separate iframe) // pointer events will be sent to the frame. When dragging the margins, // we don't want this to happen as it can cause the margin to stop // being draggable. this.pluginProxy_.setPointerEvents(!e.detail); } /** * @param e Contains information about where the plugin should scroll to. */ private onTextFocusPosition_(e: CustomEvent<{x: number, y: number}>) { // TODO(tkent): This is a workaround of a preview-area scrolling // issue. Blink scrolls preview-area on focus, but we don't want it. We // should adjust scroll position of PDF preview and positions of // MarginContgrols here, or restructure the HTML so that the PDF review // and MarginControls are on the single scrollable container. // crbug.com/601341 this.scrollTop = 0; this.scrollLeft = 0; const position = e.detail; if (position.x === 0 && position.y === 0) { return; } this.pluginProxy_.scrollPosition(position.x, position.y); } /** * @return Whether margin settings are valid for the print ticket. */ private marginsValid_(): boolean { const type = this.getSettingValue('margins') as MarginsType; if (!Object.values(MarginsType).includes(type)) { // Unrecognized margins type. return false; } if (type !== MarginsType.CUSTOM) { return true; } const customMargins = this.getSettingValue('customMargins') as MarginsSetting; return customMargins.marginTop !== undefined && customMargins.marginLeft !== undefined && customMargins.marginBottom !== undefined && customMargins.marginRight !== undefined; } private hasTicketChanged_(): boolean { if (!this.marginsValid_()) { // Log so that we can try to debug how this occurs. See // https://crbug.com/942211 console.warn('Requested preview with invalid margins'); return false; } if (!this.lastTicket_) { return true; } const lastTicket = this.lastTicket_; // Margins const newMarginsType = this.getSettingValue('margins') as MarginsType; if (newMarginsType !== lastTicket.marginsType && newMarginsType !== MarginsType.CUSTOM) { return true; } if (newMarginsType === MarginsType.CUSTOM) { const customMargins = this.getSettingValue('customMargins') as MarginsSetting; // Change in custom margins values. if (!!lastTicket.marginsCustom && (lastTicket.marginsCustom.marginTop !== customMargins.marginTop || lastTicket.marginsCustom.marginLeft !== customMargins.marginLeft || lastTicket.marginsCustom.marginRight !== customMargins.marginRight || lastTicket.marginsCustom.marginBottom !== customMargins.marginBottom)) { return true; } // Changed to custom margins from a different margins type. if (!this.margins) { // Log so that we can try to debug how this occurs. See // https://crbug.com/942211 console.warn('Requested preview with undefined document margins'); return false; } const customMarginsChanged = Object.values(CustomMarginsOrientation).some(side => { return this.margins.get(side) !== (customMargins as MarginObject)[MARGIN_KEY_MAP.get(side)!]; }); if (customMarginsChanged) { return true; } } // Simple settings: ranges, layout, header/footer, pages per sheet, fit to // page, css background, selection only, rasterize, scaling, dpi if (!areRangesEqual( (this.getSettingValue('ranges') as Array<{to: number, from: number}>), lastTicket.pageRange) || this.getSettingValue('layout') !== lastTicket.landscape || this.getColorForTicket_() !== lastTicket.color || this.getSettingValue('headerFooter') !== lastTicket.headerFooterEnabled || this.getSettingValue('cssBackground') !== lastTicket.shouldPrintBackgrounds || this.getSettingValue('selectionOnly') !== lastTicket.shouldPrintSelectionOnly || this.getSettingValue('rasterize') !== lastTicket.rasterizePDF || this.isScalingChanged_(lastTicket)) { return true; } // Pages per sheet. If margins are non-default, wait for the return to // default margins to trigger a request. if (this.getSettingValue('pagesPerSheet') !== lastTicket.pagesPerSheet && this.getSettingValue('margins') === MarginsType.DEFAULT) { return true; } // Media size const newValue = this.getSettingValue('mediaSize') as MediaSizeValue; if (newValue.height_microns !== lastTicket.mediaSize.height_microns || newValue.width_microns !== lastTicket.mediaSize.width_microns || (this.destination.id !== lastTicket.deviceName && this.getSettingValue('margins') === MarginsType.MINIMUM)) { return true; } // Destination if (getPrinterTypeForDestination(this.destination) !== lastTicket.printerType) { return true; } return false; } /** @return Native color model of the destination. */ private getColorForTicket_(): number { return this.destination.getNativeColorModel( this.getSettingValue('color') as boolean); } /** @return Scale factor for print ticket. */ private getScaleFactorForTicket_(): number { return this.getSettingValue(this.getScalingSettingKey_()) === ScalingType.CUSTOM ? parseInt(this.getSettingValue('scaling'), 10) : 100; } /** @return Appropriate key for the scaling type setting. */ private getScalingSettingKey_(): string { return this.getSetting('scalingTypePdf').available ? 'scalingTypePdf' : 'scalingType'; } /** * @param lastTicket Last print ticket. * @return Whether new scaling settings update the previewed * document. */ private isScalingChanged_(lastTicket: PreviewTicket): boolean { // Preview always updates if the scale factor is changed. if (this.getScaleFactorForTicket_() !== lastTicket.scaleFactor) { return true; } // If both scale factors and type match, no scaling change happened. const scalingType = this.getSettingValue(this.getScalingSettingKey_()); if (scalingType === lastTicket.scalingType) { return false; } // Scaling doesn't always change because of a scalingType change. Changing // between custom scaling with a scale factor of 100 and default scaling // makes no difference. const defaultToCustom = scalingType === ScalingType.DEFAULT && lastTicket.scalingType === ScalingType.CUSTOM; const customToDefault = scalingType === ScalingType.CUSTOM && lastTicket.scalingType === ScalingType.DEFAULT; return !defaultToCustom && !customToDefault; } /** * @param dpiField The field in dpi to retrieve. * @return Field value. */ private getDpiForTicket_(dpiField: string): number { const dpi = this.getSettingValue('dpi') as {[key: string]: number}; const value = (dpi && dpiField in dpi) ? dpi[dpiField] : 0; return value; } /** * Requests a preview from the native layer. * @return Promise that resolves when the preview has been * generated. */ private getPreview_(): Promise<number> { this.inFlightRequestId_++; const ticket: PreviewTicket = { pageRange: this.getSettingValue('ranges'), mediaSize: this.getSettingValue('mediaSize'), landscape: this.getSettingValue('layout') as boolean, color: this.getColorForTicket_(), headerFooterEnabled: this.getSettingValue('headerFooter') as boolean, marginsType: this.getSettingValue('margins') as MarginsType, pagesPerSheet: this.getSettingValue('pagesPerSheet') as number, isFirstRequest: this.inFlightRequestId_ === 0, requestID: this.inFlightRequestId_, previewModifiable: this.documentModifiable, scaleFactor: this.getScaleFactorForTicket_(), scalingType: this.getSettingValue(this.getScalingSettingKey_()), shouldPrintBackgrounds: this.getSettingValue('cssBackground') as boolean, shouldPrintSelectionOnly: this.getSettingValue('selectionOnly') as boolean, // NOTE: Even though the remaining fields don't directly relate to the // preview, they still need to be included. // e.g. printing::PrintSettingsFromJobSettings() still checks for them. collate: true, copies: 1, deviceName: this.destination.id, dpiHorizontal: this.getDpiForTicket_('horizontal_dpi'), dpiVertical: this.getDpiForTicket_('vertical_dpi'), duplex: this.getSettingValue('duplex') ? DuplexMode.LONG_EDGE : DuplexMode.SIMPLEX, printerType: getPrinterTypeForDestination(this.destination), rasterizePDF: this.getSettingValue('rasterize') as boolean, }; // Set 'cloudPrintID' only if the this.destination is not local. if (this.destination && !this.destination.isLocal) { ticket.cloudPrintID = this.destination.id; } if (this.getSettingValue('margins') === MarginsType.CUSTOM) { ticket.marginsCustom = this.getSettingValue('customMargins'); } this.lastTicket_ = ticket; this.dispatchEvent(new CustomEvent( 'preview-start', {bubbles: true, composed: true, detail: this.inFlightRequestId_})); return this.nativeLayer_!.getPreview(JSON.stringify(ticket)); } private onStateOrErrorChange_() { if ((this.state === State.ERROR || this.state === State.FATAL_ERROR) && this.getErrorMessage_() !== '') { this.previewState = PreviewAreaState.ERROR; } } /** @return The error message to display in the preview area. */ private getErrorMessage_(): string { switch (this.error) { case Error.INVALID_PRINTER: return this.i18nAdvanced('invalidPrinterSettings', { substitutions: [], tags: ['BR'], }); case Error.UNSUPPORTED_PRINTER: return this.i18nAdvanced('unsupportedCloudPrinter', { substitutions: [], tags: ['BR'], }); // <if expr="chromeos or lacros"> case Error.NO_DESTINATIONS: return this.i18n('noDestinationsMessage'); // </if> case Error.PREVIEW_FAILED: return this.i18n('previewFailed'); default: return ''; } } } customElements.define( PrintPreviewPreviewAreaElement.is, PrintPreviewPreviewAreaElement);
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { TriggerSet } from '../../../../../types/trigger'; export interface Data extends RaidbossData { stockpileCount: number; mainTank?: string; } const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.AlexanderTheEyesOfTheCreatorSavage, timelineFile: 'a9s.txt', initData: () => { return { stockpileCount: 0, }; }, timelineTriggers: [ { id: 'A9S Panzerschreck', regex: /Panzerschreck/, beforeSeconds: 5, response: Responses.aoe(), }, { id: 'A9S Power Generator', regex: /Power Generator/, infoText: (data, _matches, output) => { const outputs: { [index: number]: string } = { 1: output.oneEachNWSE!(), 2: output.twoNW!(), // 3: faust, 4: output.oneNW!(), 5: output.twoSE!(), 6: output.oneNW!(), 7: output.twoSE!(), 8: output.oneNW!(), }; return outputs[data.stockpileCount]; }, outputStrings: { oneEachNWSE: { en: 'Place Generators NW/SE', de: 'Plaziere Generatoren NW/SO', fr: 'Placez les Générateurs NO/SE', ja: 'パワージェネレーターを北西/南東に運ぶ', cn: '搬运发电器到西北/东南', ko: '발전기 놓기: 북서/남동', }, twoNW: { en: 'Place Generators NW', de: 'Plaziere Generatoren NW', fr: 'Placez les Générateurs NO', ja: 'パワージェネレーターを北西に運ぶ', cn: '搬运发电器到西北', ko: '발전기 놓기: 북서', }, oneNW: { en: 'Place Generator NW', de: 'Plaziere Generator NW', fr: 'Placez les Générateurs NO', ja: 'パワージェネレーターを北西に運ぶ', cn: '搬运发电器到西北', ko: '발전기 놓기: 북서/남동', }, twoSE: { en: 'Place Generators SE', de: 'Plaziere Generatoren SO', fr: 'Placez les Générateurs SE', ja: 'パワージェネレーターを南東に運ぶ', cn: '搬运发电器到东南', ko: '발전기 놓기: 남동', }, }, }, { id: 'A9S Alarum', regex: /Alarum/, delaySeconds: 1, infoText: (data, _matches, output) => { const outputs: { [index: number]: string } = { 5: output.southeast!(), 6: output.southwest!(), 7: output.southeast!(), 8: output.southwest!(), }; return outputs[data.stockpileCount]; }, outputStrings: { southeast: { // .. or anywhere not NW en: 'Kill Alarum SE', de: 'SO Alarm besiegen', fr: 'Tuez l\'Alarum SE', ja: '南東のアラームを倒す', cn: '在东南击杀警报', ko: '남동쪽 경보기 없애기', }, southwest: { // ... or anywhere not NW/SE en: 'Kill Alarum SW', de: 'SW Alarm besiegen', fr: 'Tuez l\'Alarum SO', ja: '南西のアラームを倒す', cn: '在西南击杀警报', ko: '남서쪽 경보기 없애기', }, }, }, { id: 'A9S Bomb Explosion', regex: /Explosion/, beforeSeconds: 7, infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Bombs Soon', de: 'Bomben bald', fr: 'Bombes bientôt', ja: 'まもなく爆弾', cn: '炸弹马上爆炸', ko: '곧 폭탄 폭발', }, }, }, ], triggers: [ { id: 'A9S Stockpile Count', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Refurbisher 0', id: '1A38', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Rekompositor', id: '1A38', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Récupérateur', id: '1A38', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'リファビッシャー', id: '1A38', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '废品翻新装置', id: '1A38', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '재생자', id: '1A38', capture: false }), run: (data) => data.stockpileCount++, }, { id: 'A9S Scrapline', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Refurbisher 0', id: '1A3C', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Rekompositor', id: '1A3C', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Récupérateur', id: '1A3C', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'リファビッシャー', id: '1A3C', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '废品翻新装置', id: '1A3C', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '재생자', id: '1A3C', capture: false }), alertText: (data, _matches, output) => { if (data.mainTank === data.me) return; return output.getBehind!(); }, infoText: (data, _matches, output) => { if (data.mainTank !== data.me) return; return output.scraplineOnYou!(); }, outputStrings: { scraplineOnYou: { en: 'Scrapline on YOU', de: 'Schrottlinie auf DIR', fr: 'Corde à ferraille sur VOUS', ja: '自分にスクラップラリアット', cn: '死刑', ko: '후려갈기기 대상자', }, getBehind: { en: 'Get Behind', de: 'Hinter ihn', fr: 'Passez derrière', ja: '背面へ', cn: '去背后', ko: '보스 뒤로', }, }, }, { id: 'A9S Double Scrapline', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Refurbisher 0', id: '1A3D', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Rekompositor', id: '1A3D', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Récupérateur', id: '1A3D', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'リファビッシャー', id: '1A3D', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '废品翻新装置', id: '1A3D', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '재생자', id: '1A3D', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Stand in Alarum Puddle', de: 'In Alarm Fläche stehen', fr: 'Placez-vous dans la zone de l\'Alarum', ja: '紫色の沼に入る', cn: '站进紫色圈圈', ko: '경보기 장판 밟기', }, }, }, { id: 'A9S Scrap Rock', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017' }), condition: Conditions.targetIsYou(), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Rock on YOU', de: 'Stein auf DIR', fr: 'Rocher sur VOUS', ja: '自分に落石', cn: '落石点名', ko: '돌 징 대상자', }, }, }, { id: 'A9S Scrap Burst', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017', capture: false }), delaySeconds: 5, suppressSeconds: 1, alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Hide Fully Behind Rock', de: 'Komplett hinter dem Stein verstecken', fr: 'Cachez-vous derrière le rocher', ja: '壁の後ろに', cn: '躲在石头后', ko: '돌 뒤에 숨기', }, }, }, { id: 'A9S Scrap Bomb Stack', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '003E' }), // TODO: dubious to tell the person tanking to do it here. // But maybe fine to inform. response: Responses.stackMarkerOn(), }, { id: 'A9S Spread', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '000E' }), condition: Conditions.targetIsYou(), response: Responses.spread(), }, { id: 'A9S Auto', type: 'Ability', netRegex: NetRegexes.ability({ source: 'Refurbisher 0', id: '1AFE' }), netRegexDe: NetRegexes.ability({ source: 'Rekompositor', id: '1AFE' }), netRegexFr: NetRegexes.ability({ source: 'Récupérateur', id: '1AFE' }), netRegexJa: NetRegexes.ability({ source: 'リファビッシャー', id: '1AFE' }), netRegexCn: NetRegexes.ability({ source: '废品翻新装置', id: '1AFE' }), netRegexKo: NetRegexes.ability({ source: '재생자', id: '1AFE' }), run: (data, matches) => data.mainTank = matches.target, }, { id: 'A9S Power Generator Add Tether', type: 'Tether', netRegex: NetRegexes.tether({ id: '0011', capture: false }), suppressSeconds: 30, infoText: (data, _matches, output) => { // Some of the last phases have multiple options. // This is an old fight, so just pick one for people. const outputs: { [index: number]: string } = { 1: output.northeast!(), 2: output.southeast!(), // 3: faust, 4: output.southwest!(), 5: output.northwest!(), 6: output.southwest!(), 7: output.northwest!(), 8: output.southwest!(), }; return outputs[data.stockpileCount]; }, outputStrings: { northeast: { en: 'Adds to NE Lava', de: 'Adds in NO Lava', fr: 'Adds dans la lave NE', ja: '北東でパワージェネレーターを倒す', cn: '拉小怪到东北击杀', ko: '쫄을 북동쪽 용암으로', }, southeast: { en: 'Adds to SE Lava', de: 'Adds in SO Lava', fr: 'Adds dans la lave SE', ja: '南東でパワージェネレーターを倒す', cn: '拉小怪到东南击杀', ko: '쫄을 남동쪽 용암으로', }, southwest: { en: 'Adds to SW Lava', de: 'Adds in SW Lava', fr: 'Adds dans la lave SO', ja: '南西でパワージェネレーターを倒す', cn: '拉小怪到西南击杀', ko: '쫄을 남서쪽 용암으로', }, northwest: { en: 'Adds to NW Lava', de: 'Adds in NW Lava', fr: 'Adds dans la lave NO', ja: '北西でパワージェネレーターを倒す', cn: '拉小怪到西北击杀', ko: '쫄을 북서쪽 용암으로', }, }, }, ], timelineReplace: [ { 'locale': 'de', 'replaceSync': { 'Bomb': 'Bombe', 'Faust Z': 'Endfaust', 'Full-Metal Faust': 'Vollmetall-Faust', 'Refurbisher 0': 'Rekompositor', 'Scrap': 'Verschrotten', 'The Cranial Plate': 'Schädeldecke', 'Life Support': 'Wiederaufbereitungsanlage', }, 'replaceText': { '--rocks fall--': '--Felsen fallen--', 'Acid Rain': 'Säureregen', 'Alarum': 'Alarm', '(?<!Scrap )Bomb(?!e)': 'Bombe', 'Explosion': 'Explosion', 'Full-Metal Faust Add': 'Vollmetall-Faust Add', 'Heat Shielding Reassembly': 'Hitzeschild-Regeneration', 'Kaltstrahl': 'Kaltstrahl', 'Lava': 'Lava', 'Left Arm Reassembly': 'Linke Regeneration', 'Panzer Vor': 'Panzer vor', 'Panzerschreck': 'Panzerschreck', 'Power Generator': 'Generator', 'Right Arm Reassembly': 'Rechte Regeneration', 'Scrap Bomb': 'Schrottbombe', 'Scrap Burst': 'Schrottknall', 'Scrap Storm': 'Schrottsprengung', 'Scrap(?! )': 'Verschrotten', 'Stockpile': 'Absorption', }, }, { 'locale': 'fr', 'replaceSync': { 'Bomb': 'Bombe', 'Faust Z': 'Endfaust', 'Full-Metal Faust': 'Eisernfaust', 'Life Support': 'la chambre de recyclage CR', 'Refurbisher 0': 'Récupérateur', 'Scrap': 'Ferraille', 'The Cranial Plate': 'pont nasal', }, 'replaceText': { '\\(NE/SW\\)': '(NE/SO)', '\\(NW\\)': '(NO)', '\\(NW/SE\\)': '(NO/SE)', '\\(SW\\)': '(SO)', '(?<!Double )Scrapline': 'Corde à ferraille', '(?<!Scrap )Bomb(?!e)': 'Bombe', '--rocks fall--': '--chute des rochers--', 'Acid Rain': 'Pluie acide', 'Alarum': 'Alarum', 'Double Scrapline': 'Double corde à ferraille', 'Explosion': 'Explosion', 'Full-Metal Faust Add': 'Add Eisernfaust', 'Heat Shielding Reassembly': 'Régénération du bouclier thermique', 'Kaltstrahl': 'Kaltstrahl', 'Lava': 'Lave', 'Left Arm Reassembly': 'Régénération du bras gauche', 'Panzer Vor': 'Panzer Vor', 'Panzerschreck': 'Panzerschreck', 'Power Generator': 'Générateur d\'énergie', 'Right Arm Reassembly': 'Régénération du bras droit', 'Scrap Bomb': 'Bombe de ferraille', 'Scrap Burst': 'Déflagration de ferraille', 'Scrap Storm': 'Tempête de ferraille', 'Scrap(?! |line)': 'Ferraille', 'Stockpile': 'Agglomération', }, }, { 'locale': 'ja', 'replaceSync': { 'Bomb': '爆弾', 'Faust Z': 'ファイナル・ファウスト', 'Full-Metal Faust': 'フルアーマー・ファウスト', 'Refurbisher 0': 'リファビッシャー', 'Scrap': 'スクラップパンチ', 'The Cranial Plate': '頭部甲板', 'Life Support': '再生処理室', }, 'replaceText': { '--rocks fall--': '--落石--', 'Acid Rain': '酸性雨', 'Alarum': 'アラーム', '(?<!Scrap )Bomb': '爆弾', 'Double Scrapline': 'ダブルラリアット', 'Explosion': '爆発', 'Full-Metal Faust Add': '雑魚: フルアーマー・ファウスト', 'Heat Shielding Reassembly': '装甲再生', 'Kaltstrahl': 'カルトシュトラール', 'Lava': 'ラーヴァ', 'Left Arm Reassembly': '左腕再生', 'Panzer Vor': 'パンツァーフォー', 'Panzerschreck': 'パンツァーシュレッケ', 'Power Generator': 'パワージェネレーター', 'Right Arm Reassembly': '右腕再生', 'Scrap Bomb': 'スクラップボム', 'Scrap Burst': 'スクラップバースト', 'Scrap Storm': 'スクラップストーム', 'Scrap(?! |line)': 'スクラップパンチ', '(?<! )Scrapline': 'スクラップラリアット', 'Stockpile': '吸収', }, }, { 'locale': 'cn', 'replaceSync': { 'Bomb': '炸弹', 'Faust Z': '终极浮士德', 'Full-Metal Faust': '全装甲浮士德', 'Life Support': '再生处理室', 'Refurbisher 0': '废品翻新装置', 'Scrap': '废料拳', 'The Cranial Plate': '头部甲板', }, 'replaceText': { '(?<!Double )Scrapline': '废料碎颈臂', '--rocks fall--': '--石头落下--', 'Acid Rain': '酸雨', 'Alarum': '警报', '(?<!Scrap )Bomb': '炸弹', 'Double Scrapline': '二重碎颈臂', 'Explosion': '爆炸', 'Full-Metal Faust Add': '全装甲浮士德出现', 'Heat Shielding Reassembly': '装甲再生', 'Kaltstrahl': '寒光', 'Lava': '岩浆', 'Left Arm Reassembly': '左臂再生', 'Panzer Vor': '战车前进', 'Panzerschreck': '反坦克火箭筒', 'Power Generator': '动力发生器', 'Right Arm Reassembly': '右臂再生', 'Scrap Bomb': '废料炸弹', 'Scrap Burst': '废料爆发', 'Scrap Storm': '废料风暴', 'Scrap(?! |line)': '废料拳', 'Stockpile': '吸收', }, }, { 'locale': 'ko', 'replaceSync': { 'Bomb': '폭탄', 'Faust Z': '최종형 파우스트', 'Full-Metal Faust': '완전무장 파우스트', 'Life Support': '재생처리실', 'Refurbisher 0': '재생자', 'Scrap': '고물', 'The Cranial Plate': '머리 갑판', }, 'replaceText': { '(?<!Double )Scrapline': '한팔 후려갈기기', '--rocks fall--': '--바위 낙하--', 'Acid Rain': '산성비', 'Alarum': '경보기', '(?<!Scrap )Bomb': '폭탄', 'Double Scrapline': '양팔 후려갈기기', 'Explosion': '폭발', 'Full-Metal Faust Add': '파우스트 등장', 'Heat Shielding Reassembly': '장갑 재생', 'Kaltstrahl': '냉병기 공격', 'Lava': '용암', 'Left Arm Reassembly': '왼팔 재생', 'Panzer Vor': '기갑 전진', 'Panzerschreck': '대전차포', 'Power Generator': '발전기', 'Right Arm Reassembly': '오른팔 재생', 'Scrap Bomb': '고철 폭탄', 'Scrap Burst': '고철 폭발', 'Scrap Storm': '고철 폭풍', 'Scrap(?! |line)': '고철 주먹', 'Stockpile': '흡수', }, }, ], }; export default triggerSet;
the_stack
import BigNumber from 'bignumber.js' /** * * TEST ENGINE PARAMETERS * */ const maxStrikePrice = 5000 const maxStrikeWidth = 5000 const minStrikePrice = 1 const maxAmount = 5000 const maxAmountDifference = 5000 const minAmount = 0 const maxCollateral = 10000 const minCollateral = 0 const minSpot = 0 const maxSpot = 100000000000 let usdcDecimals = 6 let wethDecimals = 18 /** * * TEST ENGINE RULES * */ enum strikePriceRule { longLessThanShort, longMoreThanShort, longEqualShort, } enum amountRule { longLessThanShort, longMoreThanShort, longEqualShort, onlyShort, onlyLong, } enum collateralRules { insufficient, exact, excess, } enum spotPriceRules { spotHighest, spotEqualHigherStrike, spotInBetweenStrikes, spotEqualLowerStrike, spotLowest, } /** * * HELPER INTERFACES * */ interface StrikePrices { longStrike: number shortStrike: number } interface Amounts { longAmount: number shortAmount: number } export interface Test { shortAmount: number longAmount: number shortStrike: number longStrike: number collateral: BigNumber netValue: BigNumber isExcess: boolean oraclePrice: number } export interface Tests { beforeExpiryPuts: Test[] afterExpiryPuts: Test[] beforeExpiryCalls: Test[] afterExpiryCalls: Test[] } export interface Result { netValue: BigNumber isExcess: boolean } /** * * HELPER FUNCTIONS * */ /** * Return a random integer from 1 to the max number passed in. * @param max */ function getRandomInt(max: number) { return Math.min(Math.floor(Math.random() * Math.floor(max)) + 1, max) } /** * Return a rounded big number which has precision matching the collateral asset * @param value */ function round(value: BigNumber, decimals: number): BigNumber { return new BigNumber(value.toFixed(decimals, BigNumber.ROUND_CEIL)) } /** * Generate a pair of strike prices based on the strike price rule passed in * @param rule */ function strikePriceGenerator(rule: strikePriceRule): StrikePrices { let longStrike = 0 const shortStrike = getRandomInt(maxStrikePrice) const strikeWidth = getRandomInt(maxStrikeWidth) if (rule == strikePriceRule.longLessThanShort) { longStrike = Math.max(shortStrike - strikeWidth, minStrikePrice) } else if (rule == strikePriceRule.longMoreThanShort) { longStrike = Math.min(shortStrike + strikeWidth, maxStrikePrice) } else { longStrike = shortStrike } return { longStrike, shortStrike, } } /** * Generate a pair of integer amounts based on the amount rule passed in * @param rule */ function amountGenerator(rule: amountRule): Amounts { let longAmount = 0 let shortAmount = getRandomInt(maxStrikePrice) const strikeWidth = getRandomInt(maxStrikeWidth) if (rule == amountRule.longLessThanShort) { longAmount = Math.max(shortAmount - strikeWidth, minAmount) } else if (rule == amountRule.longMoreThanShort) { longAmount = Math.min(shortAmount + strikeWidth, maxAmount) } else if (rule == amountRule.onlyShort) { longAmount = 0 } else if (rule == amountRule.onlyLong) { longAmount = shortAmount shortAmount = 0 } else { longAmount = shortAmount } return { longAmount, shortAmount, } } /** * Calculate the expected put margin required before expiry for a given vault * @param strikePrices The strike prices of the short and long option * @param amounts The amount of the short and the long option */ function putMarginRequiredBeforeExpiry(strikePrices: StrikePrices, amounts: Amounts): BigNumber { const shortStrike = new BigNumber(strikePrices.shortStrike) const longStrike = new BigNumber(strikePrices.longStrike) const shortAmount = new BigNumber(amounts.shortAmount) const longAmount = new BigNumber(amounts.longAmount) const netValue = shortStrike.times(shortAmount).minus(longStrike.times(BigNumber.min(shortAmount, longAmount))) return BigNumber.max(0, netValue) } /** * Calculate the expected put margin required after expiry for a given vault * @param strikePrices The strike prices of the short and long option * @param amounts The amount of the short and the long option */ function putMarginRequiredAfterExpiry(spotPrice: number, strikePrices: StrikePrices, amounts: Amounts): BigNumber { const shortStrike = new BigNumber(strikePrices.shortStrike) const longStrike = new BigNumber(strikePrices.longStrike) const shortAmount = new BigNumber(amounts.shortAmount) const longAmount = new BigNumber(amounts.longAmount) const longCashValue = BigNumber.max(0, longStrike.minus(spotPrice)).times(longAmount) const shortCashValue = BigNumber.max(0, shortStrike.minus(spotPrice)).times(shortAmount) return shortCashValue.minus(longCashValue) } /** * Calculate the expected call margin required after expiry for a given vault * @param strikePrices The strike prices of the short and long option * @param amounts The amount of the short and the long option */ export function callMarginRequiredBeforeExpiry(strikePrices: StrikePrices, amounts: Amounts): BigNumber { const shortStrike = new BigNumber(strikePrices.shortStrike) const longStrike = new BigNumber(strikePrices.longStrike) const shortAmount = new BigNumber(amounts.shortAmount) const longAmount = new BigNumber(amounts.longAmount) const netValue = BigNumber.max( longStrike.minus(shortStrike).times(shortAmount).dividedBy(longStrike), BigNumber.max(shortAmount.minus(longAmount), 0), ) return round(netValue, wethDecimals) } /** * Calculate the expected call margin required after expiry for a given vault * @param strikePrices The strike prices of the short and long option * @param amounts The amount of the short and the long option */ function callMarginRequiredAfterExpiry(spotPrice: number, strikePrices: StrikePrices, amounts: Amounts): BigNumber { const shortStrike = new BigNumber(strikePrices.shortStrike) const longStrike = new BigNumber(strikePrices.longStrike) const shortAmount = new BigNumber(amounts.shortAmount) const longAmount = new BigNumber(amounts.longAmount) const bnSpotPrice = new BigNumber(spotPrice) const longCashValue = BigNumber.max(0, bnSpotPrice.minus(longStrike)).times(longAmount) const shortCashValue = BigNumber.max(0, bnSpotPrice.minus(shortStrike)).times(shortAmount) return round(shortCashValue.minus(longCashValue).div(bnSpotPrice), wethDecimals) } /** * TEST CASE GENERATORS * The following functions are where the math calculations on expected test case results happen */ /** * Create a test for a vault with call options which have expired * @param rule The rule on what the spot price of the option is * @param strikePrices The strike prices of the short and long option in the vault * @param amounts The amount of the short and the long option in the vault * @param collateral The amount of collateral in the vault */ function callAfterExpiryTestCreator( rule: spotPriceRules, strikePrices: StrikePrices, amounts: Amounts, collateral: BigNumber, ): Test { const highStrike = Math.max(strikePrices.shortStrike, strikePrices.longStrike) const lowStrike = Math.min(strikePrices.shortStrike, strikePrices.longStrike) let spotPrice = 0 if (rule == spotPriceRules.spotHighest) { spotPrice = Math.min(getRandomInt(maxSpot) + highStrike, maxSpot) } else if (rule == spotPriceRules.spotEqualHigherStrike) { spotPrice = highStrike } else if (rule == spotPriceRules.spotInBetweenStrikes) { const spotPriceDifference = highStrike - lowStrike spotPrice = getRandomInt(spotPriceDifference) + lowStrike } else if (rule == spotPriceRules.spotEqualLowerStrike) { spotPrice = lowStrike } else if (rule == spotPriceRules.spotLowest) { spotPrice = Math.max(getRandomInt(lowStrike), minSpot) } const netValue = collateral.minus(callMarginRequiredAfterExpiry(spotPrice, strikePrices, amounts)) return { shortAmount: amounts.shortAmount, longAmount: amounts.longAmount, shortStrike: strikePrices.shortStrike, longStrike: strikePrices.longStrike, collateral: collateral, netValue: netValue, isExcess: true, oraclePrice: spotPrice, } } /** * Create a test for a vault with put options which have expired * @param rule The rule on what the spot price of the option is * @param strikePrices The strike prices of the short and long option in the vault * @param amounts The amount of the short and the long option in the vault * @param collateral The amount of collateral in the vault */ function putAfterExpiryTestCreator( rule: spotPriceRules, strikePrices: StrikePrices, amounts: Amounts, collateral: BigNumber, ): Test { const highStrike = Math.max(strikePrices.shortStrike, strikePrices.longStrike) const lowStrike = Math.min(strikePrices.shortStrike, strikePrices.longStrike) let spotPrice = 0 if (rule == spotPriceRules.spotHighest) { spotPrice = Math.min(getRandomInt(maxSpot) + highStrike, maxSpot) } else if (rule == spotPriceRules.spotEqualHigherStrike) { spotPrice = highStrike } else if (rule == spotPriceRules.spotInBetweenStrikes) { const spotPriceDifference = highStrike - lowStrike spotPrice = getRandomInt(spotPriceDifference) + lowStrike } else if (rule == spotPriceRules.spotEqualLowerStrike) { spotPrice = lowStrike } else if (rule == spotPriceRules.spotLowest) { spotPrice = Math.max(getRandomInt(lowStrike), minSpot) } const netValue = collateral.minus(putMarginRequiredAfterExpiry(spotPrice, strikePrices, amounts)) return { shortAmount: amounts.shortAmount, longAmount: amounts.longAmount, shortStrike: strikePrices.shortStrike, longStrike: strikePrices.longStrike, collateral: collateral, netValue: netValue, isExcess: true, oraclePrice: spotPrice, } } /** * Create a test for a vault with put options which have not expired * @param rule The rule on how much collateral there should be in the vault * @param strikePrices The strike prices of the short and long option in the vault * @param amounts The amount of the short and the long option in the vault */ function putBeforExpiryTestCreator(rule: collateralRules, strikePrices: StrikePrices, amounts: Amounts): Test { const marginRequired = putMarginRequiredBeforeExpiry(strikePrices, amounts) let collateral = marginRequired if (rule == collateralRules.insufficient) { const amountToRemove = getRandomInt(collateral.toNumber()) collateral = BigNumber.max(minCollateral, collateral.minus(amountToRemove)) } else if (rule == collateralRules.excess) { const excess = getRandomInt(maxCollateral) collateral = BigNumber.min(maxCollateral, collateral.plus(excess)) } const netValue = collateral.minus(marginRequired) const isExcess = netValue.gte(0) return { shortAmount: amounts.shortAmount, longAmount: amounts.longAmount, shortStrike: strikePrices.shortStrike, longStrike: strikePrices.longStrike, collateral: collateral, netValue: netValue.abs(), isExcess: isExcess, oraclePrice: 0, } } /** * Create a test for a vault with call options which have not expired * @param rule The rule on how much collateral there should be in the vault * @param strikePrices The strike prices of the short and long option in the vault * @param amounts The amount of the short and the long option in the vault */ function callBeforExpiryTestCreator(rule: collateralRules, strikePrices: StrikePrices, amounts: Amounts): Test { const marginRequired = callMarginRequiredBeforeExpiry(strikePrices, amounts) let collateral = marginRequired if (rule == collateralRules.insufficient) { const amountToRemove = getRandomInt(collateral.toNumber()) collateral = BigNumber.max(new BigNumber(minCollateral), collateral.minus(amountToRemove)) } else if (rule == collateralRules.excess) { const excess = getRandomInt(maxCollateral) collateral = BigNumber.min(new BigNumber(maxCollateral), collateral.plus(excess)) } const netValue = collateral.minus(marginRequired) const isExcess = netValue.gte(0) return { shortAmount: amounts.shortAmount, longAmount: amounts.longAmount, shortStrike: strikePrices.shortStrike, longStrike: strikePrices.longStrike, collateral: collateral, netValue: netValue.abs(), isExcess: isExcess, oraclePrice: 0, } } /** * Create an series of tests for all the various rules specified based on the parameters specified. * Return an array of tests for puts before expiry, puts after expiry. */ export function testCaseGenerator(putUnderlyingDecimals = 6, callUnderlyingDecimals = 18): Tests { usdcDecimals = putUnderlyingDecimals wethDecimals = callUnderlyingDecimals const putTestsBeforeExpiry: Test[] = [] const putTestsAfterExpiry: Test[] = [] const callTestsBeforeExpiry: Test[] = [] const callTestsAfterExpiry: Test[] = [] for (let i = 0; i < Object.keys(strikePriceRule).length / 2; i++) { for (let j = 0; j < Object.keys(amountRule).length / 2; j++) { for (let k = 0; k < Object.keys(collateralRules).length / 2; k++) { const testStrikes = strikePriceGenerator(i) const testAmounts = amountGenerator(j) let putTest = putBeforExpiryTestCreator(k, testStrikes, testAmounts) putTestsBeforeExpiry.push(putTest) let callTest = callBeforExpiryTestCreator(k, testStrikes, testAmounts) callTestsBeforeExpiry.push(callTest) // create put and call after expiry tests assuming vault is exactly collateralized. if (collateralRules.exact == k) { for (let l = 0; l < Object.keys(spotPriceRules).length / 2; l++) { putTest = putAfterExpiryTestCreator(l, testStrikes, testAmounts, putTest.collateral) putTestsAfterExpiry.push(putTest) callTest = callAfterExpiryTestCreator(l, testStrikes, testAmounts, callTest.collateral) callTestsAfterExpiry.push(callTest) } } } } } return { beforeExpiryPuts: putTestsBeforeExpiry, afterExpiryPuts: putTestsAfterExpiry, beforeExpiryCalls: callTestsBeforeExpiry, afterExpiryCalls: callTestsAfterExpiry, } } /** ERROR REPORTING HELPERS */ /** * Return an error message to be emitted for the passed in test * @param test The generated test case */ export function testToString(test: Test, actualValue?: BigNumber): string { const strikePrice = '\n Long Strike = $' + test.longStrike.toString() + '\n Short Strike = $' + test.shortStrike.toString() const amount = '\n Long Amount = ' + test.longAmount.toString() + '\n Short Amount = ' + test.shortAmount.toString() const collateral = '\n Collateral = ' + test.collateral.toString() const oraclePrice = test.oraclePrice > 0 ? '\n Oracle Price = ' + test.oraclePrice.toString() : '' const actualVal = actualValue ? 'Actual Value = ' + actualValue : '' const expectedResult = '\n\n EXPECTED RESULT: \n\n netValue = ' + test.netValue.toString() + '\n isExcess = ' + test.isExcess.toString() return '\n TEST FAILED: \n' + strikePrice + amount + collateral + oraclePrice + expectedResult + actualVal + '\n \n' }
the_stack
import { HassEntity } from "home-assistant-js-websocket"; import { BINARY_STATE_OFF, BINARY_STATE_ON, DOMAINS_WITH_DYNAMIC_PICTURE, } from "../common/const"; import { computeDomain } from "../common/entity/compute_domain"; import { computeStateDisplay } from "../common/entity/compute_state_display"; import { computeStateDomain } from "../common/entity/compute_state_domain"; import { LocalizeFunc } from "../common/translations/localize"; import { HaEntityPickerEntityFilterFunc } from "../components/entity/ha-entity-picker"; import { HomeAssistant } from "../types"; import { UNAVAILABLE_STATES } from "./entity"; const LOGBOOK_LOCALIZE_PATH = "ui.components.logbook.messages"; export const CONTINUOUS_DOMAINS = ["counter", "proximity", "sensor"]; export interface LogbookStreamMessage { events: LogbookEntry[]; start_time?: number; // Start time of this historical chunk end_time?: number; // End time of this historical chunk partial?: boolean; // Indiciates more historical chunks are coming } export interface LogbookEntry { // Base data when: number; // Python timestamp. Do *1000 to get JS timestamp. name: string; message?: string; entity_id?: string; icon?: string; source?: string; // The trigger source domain?: string; state?: string; // The state of the entity // Context data context_id?: string; context_user_id?: string; context_event_type?: string; context_domain?: string; context_service?: string; // Service calls only context_entity_id?: string; context_entity_id_name?: string; // Legacy, not longer sent context_name?: string; context_state?: string; // The state of the entity context_source?: string; // The trigger source context_message?: string; } // // Localization mapping for all the triggers in core // in homeassistant.components.homeassistant.triggers // const triggerPhrases = { "numeric state of": "triggered_by_numeric_state_of", // number state trigger "state of": "triggered_by_state_of", // state trigger event: "triggered_by_event", // event trigger time: "triggered_by_time", // time trigger "time pattern": "triggered_by_time_pattern", // time trigger "Home Assistant stopping": "triggered_by_homeassistant_stopping", // stop event "Home Assistant starting": "triggered_by_homeassistant_starting", // start event }; const DATA_CACHE: { [cacheKey: string]: { [entityId: string]: Promise<LogbookEntry[]> }; } = {}; export const getLogbookDataForContext = async ( hass: HomeAssistant, startDate: string, contextId?: string ): Promise<LogbookEntry[]> => { await hass.loadBackendTranslation("device_class"); return getLogbookDataFromServer( hass, startDate, undefined, undefined, contextId ); }; export const getLogbookData = async ( hass: HomeAssistant, startDate: string, endDate: string, entityIds?: string[], deviceIds?: string[] ): Promise<LogbookEntry[]> => { await hass.loadBackendTranslation("device_class"); return deviceIds?.length ? getLogbookDataFromServer( hass, startDate, endDate, entityIds, undefined, deviceIds ) : getLogbookDataCache(hass, startDate, endDate, entityIds); }; const getLogbookDataCache = async ( hass: HomeAssistant, startDate: string, endDate: string, entityId?: string[] ) => { const ALL_ENTITIES = "*"; const entityIdKey = entityId ? entityId.toString() : ALL_ENTITIES; const cacheKey = `${startDate}${endDate}`; if (!DATA_CACHE[cacheKey]) { DATA_CACHE[cacheKey] = {}; } if (entityIdKey in DATA_CACHE[cacheKey]) { return DATA_CACHE[cacheKey][entityIdKey]; } if (entityId && DATA_CACHE[cacheKey][ALL_ENTITIES]) { const entities = await DATA_CACHE[cacheKey][ALL_ENTITIES]; return entities.filter( (entity) => entity.entity_id && entityId.includes(entity.entity_id) ); } DATA_CACHE[cacheKey][entityIdKey] = getLogbookDataFromServer( hass, startDate, endDate, entityId ); return DATA_CACHE[cacheKey][entityIdKey]; }; const getLogbookDataFromServer = ( hass: HomeAssistant, startDate: string, endDate?: string, entityIds?: string[], contextId?: string, deviceIds?: string[] ): Promise<LogbookEntry[]> => { // If all specified filters are empty lists, we can return an empty list. if ( (entityIds || deviceIds) && (!entityIds || entityIds.length === 0) && (!deviceIds || deviceIds.length === 0) ) { return Promise.resolve([]); } const params: any = { type: "logbook/get_events", start_time: startDate, }; if (endDate) { params.end_time = endDate; } if (entityIds?.length) { params.entity_ids = entityIds; } if (deviceIds?.length) { params.device_ids = deviceIds; } if (contextId) { params.context_id = contextId; } return hass.callWS<LogbookEntry[]>(params); }; export const subscribeLogbook = ( hass: HomeAssistant, callbackFunction: (message: LogbookStreamMessage) => void, startDate: string, endDate: string, entityIds?: string[], deviceIds?: string[] ): Promise<() => Promise<void>> => { // If all specified filters are empty lists, we can return an empty list. if ( (entityIds || deviceIds) && (!entityIds || entityIds.length === 0) && (!deviceIds || deviceIds.length === 0) ) { return Promise.reject("No entities or devices"); } const params: any = { type: "logbook/event_stream", start_time: startDate, end_time: endDate, }; if (entityIds?.length) { params.entity_ids = entityIds; } if (deviceIds?.length) { params.device_ids = deviceIds; } return hass.connection.subscribeMessage<LogbookStreamMessage>( (message) => callbackFunction(message), params ); }; export const clearLogbookCache = (startDate: string, endDate: string) => { DATA_CACHE[`${startDate}${endDate}`] = {}; }; export const createHistoricState = ( currentStateObj: HassEntity, state?: string ): HassEntity => <HassEntity>(<unknown>{ entity_id: currentStateObj.entity_id, state: state, attributes: { // Rebuild the historical state by copying static attributes only device_class: currentStateObj?.attributes.device_class, source_type: currentStateObj?.attributes.source_type, has_date: currentStateObj?.attributes.has_date, has_time: currentStateObj?.attributes.has_time, // We do not want to use dynamic entity pictures (e.g., from media player) for the log book rendering, // as they would present a false state in the log (played media right now vs actual historic data). entity_picture_local: DOMAINS_WITH_DYNAMIC_PICTURE.has( computeDomain(currentStateObj.entity_id) ) ? undefined : currentStateObj?.attributes.entity_picture_local, entity_picture: DOMAINS_WITH_DYNAMIC_PICTURE.has( computeDomain(currentStateObj.entity_id) ) ? undefined : currentStateObj?.attributes.entity_picture, }, }); export const localizeTriggerSource = ( localize: LocalizeFunc, source: string ) => { for (const triggerPhrase in triggerPhrases) { if (source.startsWith(triggerPhrase)) { return source.replace( triggerPhrase, `${localize(`ui.components.logbook.${triggerPhrases[triggerPhrase]}`)}` ); } } return source; }; export const localizeStateMessage = ( hass: HomeAssistant, localize: LocalizeFunc, state: string, stateObj: HassEntity, domain: string ): string => { switch (domain) { case "device_tracker": case "person": if (state === "not_home") { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_away`); } if (state === "home") { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_at_home`); } return localize(`${LOGBOOK_LOCALIZE_PATH}.was_at_state`, "state", state); case "sun": return state === "above_horizon" ? localize(`${LOGBOOK_LOCALIZE_PATH}.rose`) : localize(`${LOGBOOK_LOCALIZE_PATH}.set`); case "binary_sensor": { const isOn = state === BINARY_STATE_ON; const isOff = state === BINARY_STATE_OFF; const device_class = stateObj.attributes.device_class; switch (device_class) { case "battery": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_low`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_normal`); } break; case "connectivity": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_connected`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_disconnected`); } break; case "door": case "garage_door": case "opening": case "window": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_opened`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_closed`); } break; case "lock": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_unlocked`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_locked`); } break; case "plug": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_plugged_in`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_unplugged`); } break; case "presence": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_at_home`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_away`); } break; case "safety": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_unsafe`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_safe`); } break; case "cold": case "gas": case "heat": case "moisture": case "motion": case "occupancy": case "power": case "problem": case "smoke": case "sound": case "vibration": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.detected_device_class`, { device_class: localize( `component.binary_sensor.device_class.${device_class}` ), }); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.cleared_device_class`, { device_class: localize( `component.binary_sensor.device_class.${device_class}` ), }); } break; case "tamper": if (isOn) { return localize(`${LOGBOOK_LOCALIZE_PATH}.detected_tampering`); } if (isOff) { return localize(`${LOGBOOK_LOCALIZE_PATH}.cleared_tampering`); } break; } break; } case "cover": switch (state) { case "open": return localize(`${LOGBOOK_LOCALIZE_PATH}.was_opened`); case "opening": return localize(`${LOGBOOK_LOCALIZE_PATH}.is_opening`); case "closing": return localize(`${LOGBOOK_LOCALIZE_PATH}.is_closing`); case "closed": return localize(`${LOGBOOK_LOCALIZE_PATH}.was_closed`); } break; case "lock": if (state === "unlocked") { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_unlocked`); } if (state === "locked") { return localize(`${LOGBOOK_LOCALIZE_PATH}.was_locked`); } break; } if (state === BINARY_STATE_ON) { return localize(`${LOGBOOK_LOCALIZE_PATH}.turned_on`); } if (state === BINARY_STATE_OFF) { return localize(`${LOGBOOK_LOCALIZE_PATH}.turned_off`); } if (UNAVAILABLE_STATES.includes(state)) { return localize(`${LOGBOOK_LOCALIZE_PATH}.became_unavailable`); } return hass.localize( `${LOGBOOK_LOCALIZE_PATH}.changed_to_state`, "state", stateObj ? computeStateDisplay(localize, stateObj, hass.locale, state) : state ); }; export const filterLogbookCompatibleEntities: HaEntityPickerEntityFilterFunc = ( entity ) => computeStateDomain(entity) !== "sensor" || (entity.attributes.unit_of_measurement === undefined && entity.attributes.state_class === undefined);
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { LongTermRetentionBackup, LongTermRetentionBackupsListByDatabaseOptionalParams, LongTermRetentionBackupsListByLocationOptionalParams, LongTermRetentionBackupsListByServerOptionalParams, LongTermRetentionBackupsListByResourceGroupDatabaseOptionalParams, LongTermRetentionBackupsListByResourceGroupLocationOptionalParams, LongTermRetentionBackupsListByResourceGroupServerOptionalParams, CopyLongTermRetentionBackupParameters, LongTermRetentionBackupsCopyOptionalParams, LongTermRetentionBackupsCopyResponse, UpdateLongTermRetentionBackupParameters, LongTermRetentionBackupsUpdateOptionalParams, LongTermRetentionBackupsUpdateResponse, LongTermRetentionBackupsGetOptionalParams, LongTermRetentionBackupsGetResponse, LongTermRetentionBackupsDeleteOptionalParams, LongTermRetentionBackupsCopyByResourceGroupOptionalParams, LongTermRetentionBackupsCopyByResourceGroupResponse, LongTermRetentionBackupsUpdateByResourceGroupOptionalParams, LongTermRetentionBackupsUpdateByResourceGroupResponse, LongTermRetentionBackupsGetByResourceGroupOptionalParams, LongTermRetentionBackupsGetByResourceGroupResponse, LongTermRetentionBackupsDeleteByResourceGroupOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a LongTermRetentionBackups. */ export interface LongTermRetentionBackups { /** * Lists all long term retention backups for a database. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param options The options parameters. */ listByDatabase( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, options?: LongTermRetentionBackupsListByDatabaseOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Lists the long term retention backups for a given location. * @param locationName The location of the database * @param options The options parameters. */ listByLocation( locationName: string, options?: LongTermRetentionBackupsListByLocationOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Lists the long term retention backups for a given server. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param options The options parameters. */ listByServer( locationName: string, longTermRetentionServerName: string, options?: LongTermRetentionBackupsListByServerOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Lists all long term retention backups for a database. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param options The options parameters. */ listByResourceGroupDatabase( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, options?: LongTermRetentionBackupsListByResourceGroupDatabaseOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Lists the long term retention backups for a given location. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database * @param options The options parameters. */ listByResourceGroupLocation( resourceGroupName: string, locationName: string, options?: LongTermRetentionBackupsListByResourceGroupLocationOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Lists the long term retention backups for a given server. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param options The options parameters. */ listByResourceGroupServer( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, options?: LongTermRetentionBackupsListByResourceGroupServerOptionalParams ): PagedAsyncIterableIterator<LongTermRetentionBackup>; /** * Copy an existing long term retention backup. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The parameters needed for long term retention copy request * @param options The options parameters. */ beginCopy( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: CopyLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsCopyOptionalParams ): Promise< PollerLike< PollOperationState<LongTermRetentionBackupsCopyResponse>, LongTermRetentionBackupsCopyResponse > >; /** * Copy an existing long term retention backup. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The parameters needed for long term retention copy request * @param options The options parameters. */ beginCopyAndWait( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: CopyLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsCopyOptionalParams ): Promise<LongTermRetentionBackupsCopyResponse>; /** * Updates an existing long term retention backup. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The requested backup resource state * @param options The options parameters. */ beginUpdate( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: UpdateLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsUpdateOptionalParams ): Promise< PollerLike< PollOperationState<LongTermRetentionBackupsUpdateResponse>, LongTermRetentionBackupsUpdateResponse > >; /** * Updates an existing long term retention backup. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The requested backup resource state * @param options The options parameters. */ beginUpdateAndWait( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: UpdateLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsUpdateOptionalParams ): Promise<LongTermRetentionBackupsUpdateResponse>; /** * Gets a long term retention backup. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ get( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsGetOptionalParams ): Promise<LongTermRetentionBackupsGetResponse>; /** * Deletes a long term retention backup. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ beginDelete( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes a long term retention backup. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ beginDeleteAndWait( locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsDeleteOptionalParams ): Promise<void>; /** * Copy an existing long term retention backup to a different server. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The parameters needed for long term retention copy request * @param options The options parameters. */ beginCopyByResourceGroup( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: CopyLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsCopyByResourceGroupOptionalParams ): Promise< PollerLike< PollOperationState<LongTermRetentionBackupsCopyByResourceGroupResponse>, LongTermRetentionBackupsCopyByResourceGroupResponse > >; /** * Copy an existing long term retention backup to a different server. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The parameters needed for long term retention copy request * @param options The options parameters. */ beginCopyByResourceGroupAndWait( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: CopyLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsCopyByResourceGroupOptionalParams ): Promise<LongTermRetentionBackupsCopyByResourceGroupResponse>; /** * Updates an existing long term retention backup. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The requested backup resource state * @param options The options parameters. */ beginUpdateByResourceGroup( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: UpdateLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsUpdateByResourceGroupOptionalParams ): Promise< PollerLike< PollOperationState<LongTermRetentionBackupsUpdateByResourceGroupResponse>, LongTermRetentionBackupsUpdateByResourceGroupResponse > >; /** * Updates an existing long term retention backup. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param parameters The requested backup resource state * @param options The options parameters. */ beginUpdateByResourceGroupAndWait( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, parameters: UpdateLongTermRetentionBackupParameters, options?: LongTermRetentionBackupsUpdateByResourceGroupOptionalParams ): Promise<LongTermRetentionBackupsUpdateByResourceGroupResponse>; /** * Gets a long term retention backup. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database. * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ getByResourceGroup( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsGetByResourceGroupOptionalParams ): Promise<LongTermRetentionBackupsGetByResourceGroupResponse>; /** * Deletes a long term retention backup. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ beginDeleteByResourceGroup( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsDeleteByResourceGroupOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes a long term retention backup. * @param resourceGroupName The name of the resource group that contains the resource. You can obtain * this value from the Azure Resource Manager API or the portal. * @param locationName The location of the database * @param longTermRetentionServerName The name of the server * @param longTermRetentionDatabaseName The name of the database * @param backupName The backup name. * @param options The options parameters. */ beginDeleteByResourceGroupAndWait( resourceGroupName: string, locationName: string, longTermRetentionServerName: string, longTermRetentionDatabaseName: string, backupName: string, options?: LongTermRetentionBackupsDeleteByResourceGroupOptionalParams ): Promise<void>; }
the_stack
import {App, Editor, EventRef, MarkdownView, Menu, Modal, Notice, Plugin, PluginSettingTab, Setting, TAbstractFile, TFile} from 'obsidian'; import {LinterSettings, Options, rules, getDisabledRules} from './rules'; import DiffMatchPatch from 'diff-match-patch'; import moment from 'moment'; import {BooleanOption, DropdownOption, MomentFormatOption, TextAreaOption, TextOption} from './option'; import dedent from 'ts-dedent'; import {stripCr} from './utils'; export default class LinterPlugin extends Plugin { settings: LinterSettings; private eventRef: EventRef; async onload() { console.log('Loading Linter plugin'); await this.loadSettings(); this.addCommand({ id: 'lint-file', name: 'Lint the current file', editorCallback: (editor) => this.runLinterEditor(editor), hotkeys: [ { modifiers: ['Mod', 'Alt'], key: 'l', }, ], }); this.addCommand({ id: 'lint-all-files', name: 'Lint all files in the vault', callback: () => { new ConfirmationModal(this.app, this).open(); }, }); this.eventRef = this.app.workspace.on('file-menu', (menu, file, source) => this.onMenuOpenCallback(menu, file, source)); this.registerEvent(this.eventRef); // Source for save setting // https://github.com/hipstersmoothie/obsidian-plugin-prettier/blob/main/src/main.ts const saveCommandDefinition = (this.app as any).commands?.commands?.[ 'editor:save-file' ]; const save = saveCommandDefinition?.callback; if (typeof save === 'function') { saveCommandDefinition.callback = () => { if (this.settings.lintOnSave) { const editor = this.app.workspace.getActiveViewOfType(MarkdownView).editor; const file = this.app.workspace.getActiveFile(); if (!this.shouldIgnoreFile(file)) { this.runLinterEditor(editor); } } }; } this.addSettingTab(new SettingTab(this.app, this)); } async onunload() { console.log('Unloading Linter plugin'); this.app.workspace.offref(this.eventRef); } async loadSettings() { this.settings = { ruleConfigs: {}, lintOnSave: false, displayChanged: true, foldersToIgnore: [], }; const data = await this.loadData(); const storedSettings = data || {}; for (const rule of rules) { this.settings.ruleConfigs[rule.name] = rule.getDefaultOptions(); if (storedSettings?.ruleConfigs && storedSettings?.ruleConfigs[rule.name]) { Object.assign(this.settings.ruleConfigs[rule.name], storedSettings.ruleConfigs[rule.name]); // For backwards compatibility, if enabled is set, copy it to the new option and remove it if (storedSettings.ruleConfigs[rule.name].Enabled !== undefined) { const newEnabledOptionName = rule.enabledOptionName(); this.settings.ruleConfigs[rule.name][newEnabledOptionName] = storedSettings.ruleConfigs[rule.name].Enabled; delete this.settings.ruleConfigs[rule.name].Enabled; } } } if (Object.prototype.hasOwnProperty.call(storedSettings, 'lintOnSave')) { this.settings.lintOnSave = storedSettings.lintOnSave; } if (Object.prototype.hasOwnProperty.call(storedSettings, 'displayChanged')) { this.settings.displayChanged = storedSettings.displayChanged; } if (Object.prototype.hasOwnProperty.call(storedSettings, 'foldersToIgnore')) { this.settings.foldersToIgnore = storedSettings.foldersToIgnore; } } async saveSettings() { await this.saveData(this.settings); } onMenuOpenCallback(menu: Menu, file: TAbstractFile, source: string) { if (file instanceof TFile && file.extension === 'md') { menu.addItem((item) => { item.setIcon('wrench-screwdriver-glyph'); item.setTitle('Lint file'); item.onClick(async (evt) => { this.runLinterFile(file); }); }); } } lintText(oldText: string, file: TFile) { let newText = oldText; const disabledRules = getDisabledRules(oldText); for (const rule of rules) { if (disabledRules.includes(rule.alias())) { continue; } const options: Options = Object.assign({ 'metadata: file created time': moment(file.stat.ctime).format(), 'metadata: file modified time': moment(file.stat.mtime).format(), 'metadata: file name': file.basename, }, rule.getOptions(this.settings)); if (options[rule.enabledOptionName()]) { newText = rule.apply(newText, options); } } return newText; } shouldIgnoreFile(file: TFile) { for (const folder of this.settings.foldersToIgnore) { if (folder.length > 0 && file.path.startsWith(folder)) { return true; } } return false; } async runLinterFile(file: TFile) { const oldText = stripCr(await this.app.vault.read(file)); try { const newText = this.lintText(oldText, file); await this.app.vault.modify(file, newText); } catch (error) { new Notice('An error occured during linting. See console for details'); console.log(`Linting error in file: ${file.path}`); console.error(error); } } async runLinterAllFiles() { await Promise.all(this.app.vault.getMarkdownFiles().map(async (file) => { if (!this.shouldIgnoreFile(file)) { await this.runLinterFile(file); } })); new Notice('Linted all files'); } runLinterEditor(editor: Editor) { console.log('running linter'); const file = this.app.workspace.getActiveFile(); const oldText = editor.getValue(); const newText = this.lintText(oldText, file); // Replace changed lines const dmp = new DiffMatchPatch.diff_match_patch(); // eslint-disable-line new-cap const changes = dmp.diff_main(oldText, newText); let curText = ''; changes.forEach((change) => { function endOfDocument(doc: string) { const lines = doc.split('\n'); return {line: lines.length - 1, ch: lines[lines.length - 1].length}; } const [type, value] = change; if (type == DiffMatchPatch.DIFF_INSERT) { editor.replaceRange(value, endOfDocument(curText)); curText += value; } else if (type == DiffMatchPatch.DIFF_DELETE) { const start = endOfDocument(curText); let tempText = curText; tempText += value; const end = endOfDocument(tempText); editor.replaceRange('', start, end); } else { curText += value; } }); const charsAdded = changes.map((change) => change[0] == DiffMatchPatch.DIFF_INSERT ? change[1].length : 0).reduce((a, b) => a + b, 0); const charsRemoved = changes.map((change) => change[0] == DiffMatchPatch.DIFF_DELETE ? change[1].length : 0).reduce((a, b) => a + b, 0); this.displayChangedMessage(charsAdded, charsRemoved); } private displayChangedMessage(charsAdded: number, charsRemoved: number) { if (this.settings.displayChanged) { const message = dedent` ${charsAdded} characters added ${charsRemoved} characters removed `; new Notice(message); } } } class SettingTab extends PluginSettingTab { plugin: LinterPlugin; constructor(app: App, plugin: LinterPlugin) { super(app, plugin); this.plugin = plugin; // Inject display functions. Necessary because the Settings object cannot be used in tests. BooleanOption.prototype.display = function(containerEl: HTMLElement, settings: LinterSettings, plugin: LinterPlugin): void { new Setting(containerEl) .setName(this.name) .setDesc(this.description) .addToggle((toggle) => { toggle.setValue(settings.ruleConfigs[this.ruleName][this.name]); toggle.onChange((value) => { this.setOption(value, settings); plugin.settings = settings; plugin.saveData(plugin.settings); }); }); }; TextOption.prototype.display = function(containerEl: HTMLElement, settings: LinterSettings, plugin: LinterPlugin): void { new Setting(containerEl) .setName(this.name) .setDesc(this.description) .addText((textbox) => { textbox.setValue(settings.ruleConfigs[this.ruleName][this.name]); textbox.onChange((value) => { this.setOption(value, settings); plugin.settings = settings; plugin.saveData(plugin.settings); }); }); }; TextAreaOption.prototype.display = function(containerEl: HTMLElement, settings: LinterSettings, plugin: LinterPlugin): void { new Setting(containerEl) .setName(this.name) .setDesc(this.description) .addTextArea((textbox) => { textbox.setValue(settings.ruleConfigs[this.ruleName][this.name]); textbox.onChange((value) => { this.setOption(value, settings); plugin.settings = settings; plugin.saveData(plugin.settings); }); }); }; MomentFormatOption.prototype.display = function(containerEl: HTMLElement, settings: LinterSettings, plugin: LinterPlugin): void { new Setting(containerEl) .setName(this.name) .setDesc(this.description) .addMomentFormat((format) => { format.setValue(settings.ruleConfigs[this.ruleName][this.name]); format.setPlaceholder('dddd, MMMM Do YYYY, h:mm:ss a'); format.onChange((value) => { this.setOption(value, settings); plugin.settings = settings; plugin.saveData(plugin.settings); }); }); }; DropdownOption.prototype.display = function(containerEl: HTMLElement, settings: LinterSettings, plugin: LinterPlugin): void { new Setting(containerEl) .setName(this.name) .setDesc(this.description) .addDropdown((dropdown) => { dropdown.setValue(settings.ruleConfigs[this.ruleName][this.name]); for (const option of this.options) { dropdown.addOption(option.value, option.value); } dropdown.onChange((value) => { this.setOption(value, settings); plugin.settings = settings; plugin.saveData(plugin.settings); }); }); }; } display(): void { const {containerEl} = this; containerEl.empty(); containerEl.createEl('h2', {text: 'General Settings'}); new Setting(containerEl) .setName('Lint on save') .setDesc('Lint the file on manual save (when `Ctrl + S` is pressed)') .addToggle((toggle) => { toggle .setValue(this.plugin.settings.lintOnSave) .onChange(async (value) => { this.plugin.settings.lintOnSave = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName('Display message on lint') .setDesc('Display the number of characters changed after linting') .addToggle((toggle) => { toggle .setValue(this.plugin.settings.displayChanged) .onChange(async (value) => { this.plugin.settings.displayChanged = value; await this.plugin.saveSettings(); }); }); new Setting(containerEl) .setName('Folders to ignore') .setDesc('Folders to ignore when linting all files or linting on save. Enter folder paths separated by newlines') .addTextArea((textArea) => { textArea .setValue(this.plugin.settings.foldersToIgnore.join('\n')) .onChange(async (value) => { this.plugin.settings.foldersToIgnore = value.split('\n'); await this.plugin.saveSettings(); }); }); let prevSection = ''; for (const rule of rules) { if (rule.type !== prevSection) { containerEl.createEl('h2', {text: rule.type}); prevSection = rule.type; } containerEl.createEl('h3', {}, (el) =>{ el.innerHTML = `<a href="${rule.getURL()}">${rule.name}</a>`; }); for (const option of rule.options) { option.display(containerEl, this.plugin.settings, this.plugin); } } } } // https://github.com/nothingislost/obsidian-workspaces-plus/blob/bbba928ec64b30b8dec7fe8fc9e5d2d96543f1f3/src/modal.ts#L68 class ConfirmationModal extends Modal { constructor(app: App, plugin: LinterPlugin) { super(app); this.modalEl.addClass('confirm-modal'); this.contentEl.createEl('h3', {text: 'Warning'}); const e: HTMLParagraphElement = this.contentEl.createEl('p', {text: 'This will edit all of your files and may introduce errors. Make sure you have backed up your files.'}); e.id = 'confirm-dialog'; this.contentEl.createDiv('modal-button-container', (buttonsEl) => { buttonsEl.createEl('button', {text: 'Cancel'}).addEventListener('click', () => this.close()); const btnSumbit = buttonsEl.createEl('button', { attr: {type: 'submit'}, cls: 'mod-cta', text: 'Lint All', }); btnSumbit.addEventListener('click', async (e) => { new Notice('Linting all files...'); this.close(); await plugin.runLinterAllFiles(); }); setTimeout(() => { btnSumbit.focus(); }, 50); }); } }
the_stack
'use strict'; import * as async from 'async'; import { AuthRequest, AuthResponse, EmailMissingHandler, ExpressHandler, IdentityProvider, TokenRequest, AccessToken, CheckRefreshDecision, TokenInfo } from './types'; import { profileStore } from './profile-store' const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:generic-router'); import * as wicked from 'wicked-sdk'; import * as request from 'request'; import * as nocache from 'nocache'; import { oauth2 } from '../kong-oauth2/oauth2'; import { tokens } from '../kong-oauth2/tokens'; const Router = require('express').Router; const qs = require('querystring'); import { utils } from './utils'; import { kongUtils } from '../kong-oauth2/kong-utils'; import { utilsOAuth2 } from './utils-oauth2'; import { failMessage, failError, failOAuth, failRedirect, makeError, failJson, makeOAuthError } from './utils-fail'; import { OidcProfile, WickedApiScopes, WickedGrant, WickedUserInfo, WickedUserCreateInfo, WickedScopeGrant, WickedNamespace, WickedCollection, WickedRegistration, PassthroughScopeResponse, Callback, PassthroughScopeRequest, WickedApi, WickedSubscriptionInfo, WickedUserShortInfo, WickedSubscription, WickedSubscriptionScopeModeType } from 'wicked-sdk'; import { GrantManager } from './grant-manager'; const ERROR_TIMEOUT = 500; // ms const EXTERNAL_URL_INTERVAL = 500; const EXTERNAL_URL_RETRIES = 10; export class GenericOAuth2Router { protected authMethodId: string; protected oauthRouter: any; protected idp: IdentityProvider; constructor(basePath: string, authMethodId: string) { debug(`constructor(${basePath}, ${authMethodId})`); this.oauthRouter = new Router(); this.authMethodId = authMethodId; this.initOAuthRouter(); const grantManager = new GrantManager(this.authMethodId); this.oauthRouter.use('/grants', grantManager.getRouter()); } public getRouter() { return this.oauthRouter; }; public initIdP(idp: IdentityProvider): void { debug(`initIdP(${idp.getType()})`); this.idp = idp; // Configure additional end points (if applicable). JavaScript is sick. const endpoints = idp.endpoints(); const standardEndpoints = [ { method: 'get', uri: '/verify/:verificationId', handler: this.createVerifyHandler(this.authMethodId) }, { method: 'post', uri: '/verify', handler: this.createVerifyPostHandler(this.authMethodId) }, { method: 'get', uri: '/verifyemail', handler: this.createVerifyEmailHandler(this.authMethodId) }, { method: 'post', uri: '/verifyemail', handler: this.createVerifyEmailPostHandler(this.authMethodId) }, { method: 'post', uri: '/grant', handler: this.createGrantPostHandler(this.authMethodId) }, { method: 'post', uri: '/selectnamespace', handler: this.createSelectNamespacePostHandler(this.authMethodId) } ]; // Spread operator, fwiw. endpoints.push(...standardEndpoints); for (let i = 0; i < endpoints.length; ++i) { const e = endpoints[i]; if (!e.uri) throw new Error('initIdP: Invalid end point definition, "uri" is null): ' + JSON.stringify(e)); if (!e.handler) throw new Error('initIdP: Invalid end point definition, "handler" is null): ' + JSON.stringify(e)); if (e.middleware) this.oauthRouter[e.method](e.uri, e.middleware, e.handler); else this.oauthRouter[e.method](e.uri, e.handler); } const instance = this; // Specific error handler for this router this.oauthRouter.use(function (err, req, res, next) { debug(`Error handler for ${instance.authMethodId}`); // Handle OAuth2 errors specifically here if (err.oauthError) { error(err); if (req.isTokenFlow) { // Return a plain error message in JSON const status = err.status || 500; return res.status(status).json({ error: err.oauthError, error_description: err.message }); } // Check for authorization calls if (utils.hasAuthRequest(req, instance.authMethodId)) { const authRequest = utils.getAuthRequest(req, instance.authMethodId); // We need an auth request to see how to answer if (authRequest && authRequest.redirect_uri) { // We must create a redirect with the error message const redirectUri = `${authRequest.redirect_uri}?error=${qs.escape(err.oauthError)}&error_description=${qs.escape(err.message)}`; return res.redirect(redirectUri); } } } // Check for links to display in the error message const errorLinks = instance.idp.getErrorLinks(); if (errorLinks) { err.errorLink = errorLinks.url; err.errorLinkDescription = errorLinks.description; } // Whatever has not been handled yet, delegate to generic error handler (app.ts) return next(err); }); } public createVerifyHandler(authMethodId: string): ExpressHandler { debug(`createVerifyEmailHandler(${authMethodId})`); // GET /verify/:verificationId return (req, res, next) => { debug(`verifyEmailHandler(${authMethodId})`); const verificationId = req.params.verificationId; wicked.getVerification(verificationId, (err, verificationInfo) => { if (err && (err.statusCode === 404 || err.status === 404)) return setTimeout(failMessage, ERROR_TIMEOUT, 404, 'The given verification ID is not valid.', next); if (err) return failError(500, err, next); if (!verificationInfo) return setTimeout(failMessage, ERROR_TIMEOUT, 404, 'The given verification ID is not valid.', next); const viewModel = utils.createViewModel(req, authMethodId, 'verify'); viewModel.email = verificationInfo.email; viewModel.id = verificationId; switch (verificationInfo.type) { case "email": return utils.render(req, res, 'verify_email', viewModel); case "lostpassword": return utils.render(req, res, 'verify_password_reset', viewModel); default: return failMessage(500, `Unknown verification type ${verificationInfo.type}`, next); } }); }; } public createVerifyPostHandler(authMethodId): ExpressHandler { debug(`createVerifyPostHandler(${authMethodId})`); return function (req, res, next): void { debug(`verifyPostHandler(${authMethodId})`); const body = req.body; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'verify'); const csrfToken = body._csrf; const verificationId = body.verification_id; const verificationType = body.type; if (!csrfToken || expectedCsrfToken !== csrfToken) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); return; } wicked.getVerification(verificationId, (err, verificationInfo) => { if (err && (err.statusCode === 404 || err.status === 404)) return setTimeout(failMessage, ERROR_TIMEOUT, 404, 'The given verification ID is not valid.', next); if (err) return failError(500, err, next); if (!verificationInfo) return setTimeout(failMessage, ERROR_TIMEOUT, 404, 'The given verification ID is not valid.', next); debug(`Successfully retrieved verification info for user ${verificationInfo.userId} (${verificationInfo.email})`); if (verificationType !== verificationInfo.type) return failMessage(500, 'Verification information found, does not match form data (type)', next); switch (verificationType) { case "email": // We're fine, we can verify the user's email address via the wicked API (as the machine user) wicked.apiPatch(`/users/${verificationInfo.userId}`, { validated: true }, null, (err, userInfo) => { if (err) return setTimeout(failError, ERROR_TIMEOUT, 500, err, next); info(`Successfully patched user, validated email for user ${verificationInfo.userId} (${verificationInfo.email})`); // Pop off a deletion of the verification, but don't wait for it. wicked.apiDelete(`/verifications/${verificationId}`, null, (err) => { if (err) error(err); }); // Success const viewModel = utils.createViewModel(req, authMethodId); return utils.render(req, res, 'verify_email_post', viewModel); }); break; case "lostpassword": const password = body.password; const password2 = body.password2; if (!password || !password2 || password !== password2 || password.length > 25 || password.length < 6) return failMessage(400, 'Invalid passwords/passwords do not match.', next); // OK, let's give this a try wicked.apiPatch(`/users/${verificationInfo.userId}`, { password: password }, null, (err, userInfo) => { if (err) return setTimeout(failError, ERROR_TIMEOUT, 500, err, next); info(`Successfully patched user, changed password for user ${verificationInfo.userId} (${verificationInfo.email})`); // Pop off a deletion of the verification, but don't wait for it. wicked.apiDelete(`/verifications/${verificationId}`, null, (err) => { if (err) error(err); }); // Success const viewModel = utils.createViewModel(req, authMethodId); return utils.render(req, res, 'verify_password_reset_post', viewModel); }); break; default: return setTimeout(failMessage, ERROR_TIMEOUT, 500, `Unknown verification type ${verificationType}`, next); } }); }; }; public createForgotPasswordHandler(authMethodId: string): ExpressHandler { debug(`createForgotPasswordHandler(${authMethodId})`); return (req, res, next) => { debug(`forgotPasswordHandler(${authMethodId})`); const viewModel = utils.createViewModel(req, authMethodId, 'forgot_password'); return utils.render(req, res, 'forgot_password', viewModel); }; } public createForgotPasswordPostHandler(authMethodId: string): ExpressHandler { debug(`createForgotPasswordPostHandler(${authMethodId})`); return function (req, res, next): void { debug(`forgotPasswordPostHandler(${authMethodId})`); const body = req.body; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'forgot_password'); const csrfToken = body._csrf; const email = body.email; if (!csrfToken || expectedCsrfToken !== csrfToken) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); return; } let emailValid = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email); if (emailValid) { // Try to retrieve the user from the database wicked.getUserByEmail(email, (err, userInfoList) => { if (err) return error(err); if (!Array.isArray(userInfoList)) return warn('forgotPasswordPostHandler: GET users by email did not return an array'); if (userInfoList.length !== 1) return warn(`forgotPasswordPostHandler: GET users by email returned a list of length ${userInfoList.length}, expected length 1`); // OK, we have exactly one user const userInfo = userInfoList[0]; info(`Issuing password reset request for user ${userInfo.id} (${userInfo.email})`); // Fire off the verification/password reset request creation (the mailer will take care // of actually sending the emails). const authUrl = utils.getExternalUrl(); const resetLink = `${authUrl}/${authMethodId}/verify/{{id}}`; const verifInfo = { type: 'lostpassword', email: userInfo.email, userId: userInfo.id, link: resetLink }; wicked.apiPost('/verifications', verifInfo, null, (err) => { if (err) return error(err); debug(`SUCCESS: Issuing password reset request for user ${userInfo.id} (${userInfo.email})`); }); }); } // No matter what happens, we will send the same page to the user. const viewModel = utils.createViewModel(req, authMethodId); utils.render(req, res, 'forgot_password_post', viewModel); }; } public createVerifyEmailHandler(authMethodId): ExpressHandler { debug(`createVerifyEmailHandler(${authMethodId})`); return (req, res, next) => { debug(`verifyEmailHandler(${authMethodId})`); // Steps: // 1. Verify that the user is logged in // 2. Display a small form // 3. Let user click a button and we will send an email (via portal-mailer) if (!utils.isLoggedIn(req, authMethodId)) { // User is not logged in; make sure we do that first return utils.loginAndRedirectBack(req, res, authMethodId); } // const redirectUri = `${req.app.get('base_url')}${authMethodId}/verifyemail`; debug(`verifyEmailHandler(${authMethodId}): User is correctly logged in.`); const viewModel = utils.createViewModel(req, authMethodId); viewModel.profile = utils.getAuthResponse(req, authMethodId).profile; return utils.render(req, res, 'verify_email_request', viewModel); }; }; createVerifyEmailPostHandler(authMethodId): ExpressHandler { debug(`createVerifyEmailPostHandler(${authMethodId})`); return (req, res, next) => { debug(`verifyEmailPostHandler(${authMethodId})`); const body = req.body; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req); const csrfToken = body._csrf; if (!utils.isLoggedIn(req, authMethodId)) return failMessage(403, 'You must be logged in to request email validation.', next); if (!csrfToken || expectedCsrfToken !== csrfToken) return setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); const profile = utils.getProfile(req, authMethodId); const email = profile.email; // If we're here, the user is not trusted (as we're asking for a validation) const trustUsers = false; utils.createVerificationRequest(trustUsers, authMethodId, email, (err) => { if (err) return failError(500, err, next); return utils.render(req, res, 'verify_email_request_confirm', utils.createViewModel(req, authMethodId)); }); }; } createEmailMissingHandler(authMethodId, continueAuthenticate): EmailMissingHandler { debug(`createEmailMissingHandler(${authMethodId})`); return async (req, res, next, customId) => { debug(`emailMissingHandler(${authMethodId})`); try { const userInfo = await utils.getUserByCustomId(customId); // Known user, and known email address? if (userInfo && userInfo.email) return continueAuthenticate(req, res, next, userInfo.email); // Unknown user, ask for email please const viewModel = utils.createViewModel(req, authMethodId); return utils.render(req, res, 'email_missing', viewModel); } catch (err) { return failError(500, err, next); } }; } createEmailMissingPostHandler(authMethodId, continueAuthenticate) { debug(`createEmailMissingPostHandler(${authMethodId})`); return (req, res, next): void => { debug(`emailMissingPostHandler(${authMethodId})`); const body = req.body; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req); const csrfToken = body._csrf; if (!csrfToken || expectedCsrfToken !== csrfToken) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); return; } const email = body.email; const email2 = body.email2; if (!email || !email2) { setTimeout(failMessage, ERROR_TIMEOUT, 400, 'Email address or confirmation not passed in.', next); return; } if (email !== email2) { setTimeout(failMessage, ERROR_TIMEOUT, 400, 'Email address and confirmation of email address do not match', next); return; } // Pass back email address to calling IdP (e.g. Twitter) return continueAuthenticate(req, res, next, email); }; } private initAuthRequest(req): AuthRequest { debug(`initAuthRequest(${this.authMethodId})`); if (!req.session) req.session = {}; if (!req.session[this.authMethodId]) req.session[this.authMethodId] = { authRequest: {} }; else // Reset the authRequest even if it's present req.session[this.authMethodId].authRequest = {}; const authRequest = req.session[this.authMethodId].authRequest; return authRequest; }; private initOAuthRouter() { debug(`initOAuthRouter(${this.authMethodId})`); const instance = this; this.oauthRouter.use(nocache()); // OAuth2 end point Authorize this.oauthRouter.get('/api/:apiId/authorize', /*csrfProtection,*/ async function (req, res, next) { const apiId = req.params.apiId; debug(`/${instance.authMethodId}/api/${apiId}/authorize`); const clientId = req.query.client_id; const responseType = req.query.response_type; const givenRedirectUri = req.query.redirect_uri; const givenState = req.query.state; const givenScope = req.query.scope; const givenPrompt = req.query.prompt; // This is not OAuth2 compliant, but needed const givenNamespace = req.query.namespace; const givenCodeChallenge = req.query.code_challenge; const givenCodeChallengeMethod = req.query.code_challenge_method; const givenPrefillUsername = req.query.prefill_username; const authRequest = instance.initAuthRequest(req); authRequest.api_id = apiId; authRequest.client_id = clientId; authRequest.response_type = responseType; authRequest.redirect_uri = givenRedirectUri; authRequest.state = givenState; authRequest.scope = givenScope; authRequest.prompt = givenPrompt; authRequest.namespace = givenNamespace; // PKCE, RFC 7636 authRequest.code_challenge = givenCodeChallenge; authRequest.code_challenge_method = givenCodeChallengeMethod; // Support prefilled username authRequest.prefill_username = givenPrefillUsername; // Validate parameters first now (TODO: This is pbly feasible centrally, // it will be the same for all Auth Methods). let subscriptionInfo: WickedSubscriptionInfo; try { subscriptionInfo = await utilsOAuth2.validateAuthorizeRequest(authRequest); } catch (err) { return next(err); } // Is it a trusted application? authRequest.trusted = subscriptionInfo.subscription.trusted; let scopeValidationResult; try { scopeValidationResult = await utilsOAuth2.validateApiScopes(authRequest.api_id, authRequest.scope, subscriptionInfo); } catch (err) { return next(err); } // Rewrite the scope to an array which resulted from the validation. // Note that this is not the granted scopes, but the scopes that this // application requests, and we have (only) validated that the scopes // are present. If the application is not trusted, it may be that we // will ask the user to grant the scope rights to the application later // on. authRequest.scope = scopeValidationResult.validatedScopes; // Did we add/change the scopes passed in? authRequest.scope_differs = scopeValidationResult.scopeDiffers; let isLoggedIn = utils.isLoggedIn(req, instance.authMethodId); // Borrowed from OpenID Connect, check for prompt request // http://openid.net/specs/openid-connect-implicit-1_0.html#RequestParameters switch (authRequest.prompt) { case 'none': if (!isLoggedIn) { // Check whether we can delegate the "prompt" to the idp if (!instance.idp.supportsPrompt()) { // Nope. We will fail now, as the user is not logged in with the authorization server // at the moment. return failRedirect('login_required', 'user must be logged in interactively, cannot authorize without logged in user.', authRequest.redirect_uri, next); } // We will continue with authorizeWithUi below, and as the IDP // claims to know how to deal with "prompt=none", we assume it does. } else { return instance.authorizeFlow(req, res, next); } warn(`Delegating prompt=none login to identity provider implementation.`); break; case 'login': // Force login; wipe session data if (isLoggedIn) { delete req.session[instance.authMethodId].authResponse; isLoggedIn = false; } break; default: warn(`Unsupported prompt parameter '${authRequest.prompt}'`); break; } // We're fine. Check for pre-existing sessions. if (isLoggedIn) { const authResponse = utils.getAuthResponse(req, instance.authMethodId); return instance.continueAuthorizeFlow(req, res, next, authResponse); } // Not logged in, or forced login; note that this can also be a "prompt=none" type of login, so it's actually // not necessarily "with UI", but normally it is. return instance.idp.authorizeWithUi(req, res, next, authRequest); }); // !!! this.oauthRouter.post('/api/:apiId/token', async function (req, res, next) { const apiId = req.params.apiId; debug(`${instance.authMethodId}/api/${apiId}/token`); // Full switch/case on things to do, for all flows // - Client Credentials -> Go to Kong and get a token // - Authorization Code -> Go to Kong and get a token // - Resource Owner Password Grant --> Check username/password/client id/secret and get a token // - Refresh Token --> Check validity of user and client --> Get a token // Remember in the request that we're in the token flow; this is needed in the // error handler to make sure we return a valid OAuth2 error JSON, in case // we encounter errors. req.isTokenFlow = true; const tokenRequest = utilsOAuth2.makeTokenRequest(req, apiId, instance.authMethodId); try { await utilsOAuth2.validateTokenRequest(tokenRequest); } catch (err) { return next(err); } try { let accessToken: AccessToken; switch (tokenRequest.grant_type) { case 'client_credentials': // This is generically available for most auth methods accessToken = await utilsOAuth2.tokenClientCredentials(tokenRequest); break; case 'authorization_code': // Use the generic version here as well accessToken = await utilsOAuth2.tokenAuthorizationCode(tokenRequest); break; case 'password': // This has to be done specifically accessToken = await instance.tokenPasswordGrant(tokenRequest); break; case 'refresh_token': // This as well accessToken = await instance.tokenRefreshToken(tokenRequest); break; default: // This should not be possible return failOAuth(400, 'unsupported_grant_type', `invalid grant type ${tokenRequest.grant_type}`, next); } // Ok, we know we have something which could work (all data) if (accessToken.error) return failOAuth(400, accessToken.error, accessToken.error_description, next); if (accessToken.session_data) { profileStore.registerTokenOrCode(accessToken, tokenRequest.api_id, accessToken.session_data, (err) => { if (err) return failError(500, err, next); delete accessToken.session_data; return res.status(200).json(accessToken); }); } else { return res.status(200).json(accessToken); } } catch (err) { return failError(400, err, next); } }); this.oauthRouter.post('/register', async (req, res, next) => { // ... debug(`/register`); // First, check the registration nonce const sessionData = utils.getSession(req, instance.authMethodId); const nonce = req.body.nonce; if (!nonce) return failMessage(400, 'Registration nonce missing.', next); if (nonce !== sessionData.registrationNonce) return failMessage(400, 'Registration nonce mismatch.', next); // OK, this looks fine. const userId = sessionData.authResponse.userId; const poolId = sessionData.authResponse.registrationPool; const regData = req.body; // The backend validates the data const authRequest = utils.getAuthRequest(req, instance.authMethodId); const namespace = authRequest.namespace; regData.namespace = namespace; try { await wicked.upsertUserRegistration(poolId, userId, req.body); } catch (err) { return failError(500, err, next); } // Go back to the registration flow now return instance.registrationFlow(poolId, req, res, next); }); /** * End point for interactive login without using the OAuth2 mechanisms; this * is used in cases where we need a logged in user, but there is none; e.g. * scope management, or verifying email addresses. * * This end point displays the provider specific login page, and requires * a redirect URL to get back to (which must be internal to this application). * In short: Use this when you need to make sure that you have a logged in user * and just need to redirect back to a page when it's done. * * Parameters: Query parameter "redirect_uri", which takes a relative path * to this application (including the base_path). */ this.oauthRouter.get('/login', async (req, res, next) => { debug('GET /login - internal login'); // Verify parameters const redirectUri = req.query.redirect_uri; if (!redirectUri) return failMessage(400, 'Missing redirect_uri query parameter.', next); // Are we already logged in? if (utils.isLoggedIn(req, instance.authMethodId)) { // Yup, let's just redirect return res.redirect(redirectUri); } // We're not yet logged in; let's do that now // Remember we're in a "special mode", so let's create a special type // of authRequest. The authRequest goes into the session. const authRequest = instance.initAuthRequest(req); authRequest.plain = true; authRequest.redirect_uri = redirectUri; return instance.idp.authorizeWithUi(req, res, next, authRequest); }); } public continueAuthorizeFlow = async (req, res, next, authResponse: AuthResponse) => { debug('continueAuthorizeFlow()'); // This is what happens here: // // 1. Check if user already exists if only customId is filled // 2. (If not) Possibly create user in local database // --> Note that if the local IdP does not want this, it // must not call continueAuthorizeFlow before the user // has actually been created (via a signup form). // 3. Check registration status // 4. If not registered, and registration is needed, display // registration form (for the API's registration pool) // 5. Check granted scopes, if not a trusted application is calling // 6. Call authorizeFlow // Extra TODO: // - Pass-through APIs do not create local users const instance = this; let authRequest; try { authRequest = utils.getAuthRequest(req, instance.authMethodId); } catch (err) { warn('Invalid state: No authRequest in session'); warn(err.stack); } if (!authRequest) { return failMessage(400, 'Unexpected callback; there is no current authorization request pending.', next); } try { await this.checkUserFromAuthResponseAsync(authResponse, authRequest.api_id); } catch (err) { return failError(500, err, next); } // Check for plain login mode (where there is no API involved) if (authRequest.plain) { if (!authRequest.redirect_uri) return failMessage(500, 'Invalid state: authRequest.redirect_uri is missing.', next); // In this case, we don't need to check for any registrations; this is actually // not possible here, as there is no API to check with. We'll just continue with // redirecting to the redirect_uri in the authRequest (see GET /login). utils.setAuthResponse(req, instance.authMethodId, authResponse); debug(`continueAuthorizeFlow(${instance.authMethodId}): Doing plain login/redirecting: ${authRequest.redirect_uri}`); return res.redirect(authRequest.redirect_uri); } // Regular mode, we have an API we want to check registration state for. if (!authRequest.api_id) return failMessage(500, 'Invalid state: API in authorization request is missing.', next); const apiId = authRequest.api_id; utils.setAuthResponse(req, instance.authMethodId, authResponse); debug('Retrieving registration info...'); // We have an identity now, do we need registrations? let poolId; try { poolId = await utils.getApiRegistrationPoolAsync(apiId); } catch (err) { return failError(500, err, next); } debug(authResponse); if (!poolId) { if (authResponse.registrationPool) delete authResponse.registrationPool; // Nope, just go ahead; use the default Profile as profile, but using the ID from wicked authResponse.profile = utils.clone(authResponse.defaultProfile) as OidcProfile; // If we have a userId, use it as sub, otherwise keep the sub (passthroughUsers mode) if (authResponse.userId) authResponse.profile.sub = authResponse.userId; return instance.authorizeFlow(req, res, next); } authResponse.registrationPool = poolId; debug(`API requires registration with pool '${poolId}', starting registration flow`); // We'll do the registrationFlow first then... return instance.registrationFlow(poolId, req, res, next); } public failAuthorizeFlow = async (req, res, next, error: string, errorDescription: string) => { debug('failAuthorizeFlow()'); debug(`error: ${error}`); debug(`errorDescription: ${errorDescription}`); const err: any = new Error(errorDescription); err.oauthError = error; return next(err); } // ============================================= // Helper methods // ============================================= private registrationFlow(poolId: string, req, res, next): void { debug('registrationFlow()'); const authResponse = utils.getAuthResponse(req, this.authMethodId); const userId = authResponse.userId; const authRequest = utils.getAuthRequest(req, this.authMethodId); // This is not necessarily filled yet, but might be in a second run of this flow: const namespace = authRequest.namespace; const instance = this; utils.getPoolInfoByApi(authRequest.api_id, function (err, poolInfo) { if (err) return failError(500, err, next); const requiresNamespace = !!poolInfo.requiresNamespace; wicked.getUserRegistrations(poolId, userId, (err, regInfos) => { if (err && err.statusCode !== 404) return failError(500, err, next); let regInfo; if (regInfos) { if (namespace) { regInfo = regInfos.items.find(r => r.namespace === namespace); } else { if (requiresNamespace) { if (regInfos.items.length === 0) return failMessage(400, 'Invalid request. For registering, a namespace must be given to enable registration (&namespace=...).', next); if (regInfos.items.length === 1) { // We want to return the namespace as well regInfo = regInfos.items[0]; authRequest.namespace = regInfo.namespace; } else { return instance.renderSelectNamespace(req, res, next, regInfos); } } else { // This pool does not require namespaces (and does not allow them) if (regInfos.items.length > 0) { if (regInfos.items.length !== 1) return failMessage(500, 'Multiple registrations detected for registration pool.', next); regInfo = regInfos.items[0]; } } } } if (!regInfo) { if (poolInfo.disableRegister) { return failMessage(403, 'Registration is not allowed, only pre-registered users can access this API.', next); } // User does not have a registration here, we need to get one return instance.renderRegister(req, res, next); } else { // User already has a registration, create a suitable profile // TODO: Here we could check for not filled required fields utilsOAuth2.makeOidcProfile(poolId, authResponse, regInfo, (err, profile) => { if (err) return failError(500, err, next); // This will override the default user profile which is already // present, but that is fine. authResponse.profile = profile; return instance.authorizeFlow(req, res, next); }); } }); }); } private renderSelectNamespace(req, res, next, regInfos: WickedCollection<WickedRegistration>) { debug(`renderSelectNamespace()`); const instance = this; debug(regInfos); async.map(regInfos.items, (ri, callback) => { debug(ri); wicked.getPoolNamespace(ri.poolId, ri.namespace, (err, namespaceInfo) => { if (err && err.statusCode !== 404) return callback(err); if (err && err.statusCode === 404) return callback(null, null); return callback(null, namespaceInfo); }); }, (err, results: WickedNamespace[]) => { if (err) return failError(500, err, next); const viewModel = utils.createViewModel(req, instance.authMethodId, 'select_namespace'); debug(results); const tmpNs = []; for (let i = 0; i < results.length; ++i) { if (results[i]) tmpNs.push(results[i]); } viewModel.namespaces = tmpNs; // Note down which namespaces are valid const namespaceList = tmpNs.map(ni => ni.namespace); debug(namespaceList); const authRequest = utils.getAuthRequest(req, instance.authMethodId); authRequest.validNamespaces = namespaceList; return utils.render(req, res, 'select_namespace', viewModel, authRequest); }); } private createSelectNamespacePostHandler(authMethodId: string): ExpressHandler { const instance = this; return async function (req, res, next) { debug(`selectNamespacePostHandler(${authMethodId})`); const body = req.body; debug(body); const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'select_namespace'); const csrfToken = body._csrf; if (!csrfToken || expectedCsrfToken !== csrfToken) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); return; } const authRequest = utils.getAuthRequest(req, authMethodId); if (!authRequest.validNamespaces) return failMessage(403, 'Invalid state; missing list of valid namespaces.', next); const validNamespaces = authRequest.validNamespaces; delete authRequest.validNamespaces; // Verify that the selected namespace is actually a valid one const namespace = body.namespace; if (validNamespaces.findIndex(ns => ns === namespace) < 0) return failMessage(400, 'Invalid namespace selected. This should not be possible.', next); authRequest.namespace = namespace; // And off you go with the registration flow again... try { const poolId = await utils.getApiRegistrationPoolAsync(authRequest.api_id); return instance.registrationFlow(poolId, req, res, next); } catch (err) { return failError(500, err, next); } }; } private renderRegister(req, res, next) { debug('renderRegister()'); const authResponse = utils.getAuthResponse(req, this.authMethodId); const authRequest = utils.getAuthRequest(req, this.authMethodId); const apiId = utils.getAuthRequest(req, this.authMethodId).api_id; debug(`API: ${apiId}`); utils.getPoolInfoByApi(apiId, (err, poolInfo) => { if (err) return failMessage(500, 'Invalid state, could not read API information for API ${apiId} to register for.', next); debug('Default profile:'); debug(authResponse.defaultProfile); const viewModel = utils.createViewModel(req, this.authMethodId, 'register'); viewModel.userId = authResponse.userId; viewModel.customId = authResponse.customId; viewModel.defaultProfile = authResponse.defaultProfile; viewModel.poolInfo = poolInfo; const nonce = utils.createRandomId(); utils.getSession(req, this.authMethodId).registrationNonce = nonce; viewModel.nonce = nonce; debug(viewModel); utils.render(req, res, 'register', viewModel, authRequest); }); } // This is called as soon as we are sure that we have a logged in user, and possibly // also a valid registration record (if applicable to the API). Now we also have to // check the scope of the authorization request, and possibly run the scopeFlow. private authorizeFlow = async (req, res, next) => { debug(`authorizeFlow(${this.authMethodId})`); const authRequest = utils.getAuthRequest(req, this.authMethodId); const authResponse = utils.getAuthResponse(req, this.authMethodId); // Check for passthrough Scope calculation const instance = this; let apiInfo; try { apiInfo = await utils.getApiInfoAsync(authRequest.api_id); } catch (err) { return failError(500, err, next); } if ((authRequest.trusted || authRequest.scope.length === 0) && !apiInfo.passthroughScopeUrl) { // We have a trusted application, or an empty scope, we will not need to check for scope grants. return instance.authorizeFlow_Step2(req, res, next); } // Normal case: We don't have a passthroughScopeUrl, and thus we need to go through the scopeFlow if (!apiInfo.passthroughScopeUrl) { return instance.scopeFlow(req, res, next); } // OK, interesting, let's ask an upstream for the scope... let scopeResponse; try { scopeResponse = await instance.resolvePassthroughScopeAsync(authRequest.scope, authResponse.profile, apiInfo.passthroughScopeUrl); } catch (err) { return failError(500, err, next); } if (!scopeResponse.allow) { let msg = 'Scope validation with external system disallowed login (property "allow" is not present or not set to true)'; if (scopeResponse.error_message) msg += `: ${scopeResponse.error_message}`; return failRedirect('access_denied', msg, authRequest.redirect_uri, next); } if (scopeResponse.authenticated_scope) authRequest.scope = scopeResponse.authenticated_scope; else authRequest.scope = []; if (scopeResponse.authenticated_userid) { authRequest.authenticated_userid = scopeResponse.authenticated_userid; authRequest.authenticated_userid_is_verbose = true; authResponse.profile.sub = scopeResponse.authenticated_userid; } // And off we go return instance.authorizeFlow_Step2(req, res, next); } private resolvePassthroughScopeAsync = async (scope: any, profile: OidcProfile, url: string): Promise<PassthroughScopeResponse> => { const instance = this; return new Promise<PassthroughScopeResponse>(function (resolve, reject) { instance.resolvePassthroughScope(scope, profile, url, function (err, result) { err ? reject(err) : resolve(result); }); }) } private resolvePassthroughScope(scope: any, profile: OidcProfile, url: string, callback: Callback<PassthroughScopeResponse>): void { debug(`resolvePassthroughScope()`); const scopeRequest: PassthroughScopeRequest = { scope: scope, auth_method: this.authMethodId, profile: profile } async.retry({ times: EXTERNAL_URL_RETRIES, interval: EXTERNAL_URL_INTERVAL }, function (callback) { debug(`resolvePassthroughScope: Attempting to get scope at ${url}`); request.post({ url: url, body: scopeRequest, json: true, timeout: 5000 }, (err, res, body) => { if (err) return callback(err); if (res.statusCode < 200 || res.statusCode > 299) return callback(makeError('Scope resolving via external service failed with unexpected status code.', res.statusCode)); const scopeResponse = utils.getJson(body) as PassthroughScopeResponse; return callback(null, scopeResponse) }); }, function (err, scopeResponse) { if (err) return callback(err); return callback(null, scopeResponse); }); } // Here we validate the scope, check for whether the user has granted the scopes to the // application or not. private scopeFlow(req, res, next): void { debug(`scopeFlow(${this.authMethodId})`); const instance = this; const authRequest = utils.getAuthRequest(req, this.authMethodId); const authResponse = utils.getAuthResponse(req, this.authMethodId); const apiId = authRequest.api_id; const clientId = authRequest.client_id; const desiredScopesList = authRequest.scope; // ["scope1", "scope2",...] // If we're not in a passthrough situation, we have a userId here (and we're not, // that's checked in authorizeFlow). const userId = authResponse.userId; // Retrieve the application info for this client_id; the client_id is attached // to the subscription (glue between API, application and plan), but we get the // application back readily when asking for the subscription. debug(`Getting subscription for client_id ${clientId}`); wicked.getSubscriptionByClientId(clientId, apiId, (err, subsInfo) => { if (err) return failError(500, err, next); const appInfo = subsInfo.application; if (!appInfo) return failMessage(500, 'scopeFlow: Could not retrieve application info from client_id', next); debug(`Successfully retrieved subscription for client_id ${clientId}:`); debug(subsInfo); // Let's check whether the user already has some grants wicked.getUserGrant(userId, appInfo.id, apiId, (err, grantsInfo) => { if (err && err.status !== 404 && err.statusCode !== 404) return failError(500, err, next); // Unexpected error if (err || !grantsInfo) { // if err --> status 404 // Create a new grantsInfo object, it's not present grantsInfo = { grants: [] }; } const grantsList = grantsInfo.grants; // Returns a list of scope names which need to be granted access to const missingGrants = instance.diffGrants(grantsList, desiredScopesList); if (missingGrants.length === 0) { debug('All grants are already given; continue authorize flow.'); // We have all grants to scopes we need, we can continue return instance.authorizeFlow_Step2(req, res, next); } debug('Missing grants:'); debug(missingGrants); // We need additional scopes granted to the application; for that // we need to gather some information on the API (get the scope list). utils.getApiInfo(apiId, function (err, apiInfo) { if (err) return failError(500, err, next); debug('Creating view model for grant scope form'); const viewModel = utils.createViewModel(req, instance.authMethodId, 'grants'); viewModel.grantRequests = instance.makeScopeList(missingGrants, apiInfo.settings.scopes); viewModel.apiInfo = apiInfo; viewModel.appInfo = appInfo; // Store some things for later reference const sessionData = utils.getSession(req, instance.authMethodId); sessionData.grantData = { missingGrants: missingGrants, existingGrants: grantsList }; return utils.render(req, res, 'grant_scopes', viewModel, authRequest); }); }); }); } private diffGrants(storedGrants: WickedScopeGrant[], desiredScopesList: string[]): string[] { debug('diffGrants()'); const missingGrants = []; for (let i = 0; i < desiredScopesList.length; ++i) { const scope = desiredScopesList[i]; let grantedScope = storedGrants.find(g => g.scope === scope); if (!grantedScope) missingGrants.push(scope); } return missingGrants; } private makeScopeList(grantNames: string[], apiScopes: WickedApiScopes): { scope: string, description: string }[] { const scopeList: { scope: string, description: string }[] = []; for (let i = 0; i < grantNames.length; ++i) { const grantName = grantNames[i]; scopeList.push({ scope: grantName, description: apiScopes[grantName].description }); } return scopeList; } private createGrantPostHandler(authMethodId) { debug(`createGrantPostHandler(${authMethodId})`); const instance = this; return (req, res, next): void => { debug(`grantPostHandler(${authMethodId})`); const body = req.body; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'grants'); const csrfToken = body._csrf; const action = body._action; debug(`grantPostHandler(${authMethodId}, action: ${action})`); if (!csrfToken || expectedCsrfToken !== csrfToken) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'CSRF validation failed.', next); return; } if (!utils.isLoggedIn(req, authMethodId)) { setTimeout(failMessage, ERROR_TIMEOUT, 403, 'You are not logged in.', next); return; } const sessionData = utils.getSession(req, authMethodId); const grantData = sessionData.grantData; if (!grantData) { setTimeout(failMessage, ERROR_TIMEOUT, 500, 'Invalid state: Must contain grant data in session.', next); return; } const authRequest = sessionData.authRequest; const authResponse = sessionData.authResponse; if (!authRequest || !authResponse) { setTimeout(failMessage, ERROR_TIMEOUT, 500, 'Invalid state: Session must contain auth request and responses (you must be logged in)', next); return; } // Remove the grant data from the session delete sessionData.grantData; switch (action) { case "deny": warn(`User ${authResponse.userId} denied access to API ${authRequest.api_id} for application ${authRequest.app_id}, failing.`); failOAuth(403, 'access_denied', 'Access to the API was denied by the user', next); return; case "allow": info(`User ${authResponse.userId} granted access to API ${authRequest.api_id} for application ${authRequest.app_id}.`); const grantList = grantData.existingGrants; grantData.missingGrants.forEach(g => grantList.push({ scope: g })); const userGrantInfo: WickedGrant = { userId: authResponse.userId, apiId: authRequest.api_id, applicationId: authRequest.app_id, grants: grantList }; debug(userGrantInfo); wicked.apiPut(`/grants/${authResponse.userId}/applications/${authRequest.app_id}/apis/${authRequest.api_id}`, userGrantInfo, null, function (err) { if (err) return failError(500, err, next); info(`Successfully stored a grant for API ${authRequest.api_id} on behalf of user ${authResponse.userId}`); // Now delegate back to the scopeFlow, we should be fine now. return instance.scopeFlow(req, res, next); }); return; } setTimeout(failMessage, ERROR_TIMEOUT, 500, 'Invalid action, must be "deny" or "allow".', next); return; }; }; private static mergeUserGroupScope(scope: any, groups: string[]): any { debug(`addUserGroupScope(${groups ? groups.toString() : '[]'})`); if (!groups) return scope; if (groups.length === 0) return scope; let returnScope = null; if (scope && typeof (scope) === 'string') { debug('scope is a string'); returnScope = scope; if (!!returnScope) returnScope += ' '; let first = true; for (let i = 0; i < groups.length; ++i) { if (!first) returnScope += ' '; returnScope += `wicked:${groups[i]}`; first = false; } } else if ((scope && Array.isArray(scope)) || !scope) { if (!scope) returnScope = []; else returnScope = scope; for (let i = 0; i < groups.length; ++i) returnScope.push(`wicked:${groups[i]}`); } return returnScope; } private makeAuthenticatedUserId(authRequest: AuthRequest, authResponse: AuthResponse) { debug(`makeAuthenticatedUserId()`); if (authRequest.authenticated_userid && authRequest.authenticated_userid_is_verbose) return authRequest.authenticated_userid; let authenticatedUserId = `sub=${authResponse.profile.sub}`; if (authRequest.namespace) authenticatedUserId += `;namespace=${authRequest.namespace}`; return authenticatedUserId; } private authorizeFlow_Step2(req, res, next): void { debug(`authorizeFlow_Step2(${this.authMethodId})`); const authRequest = utils.getAuthRequest(req, this.authMethodId); const authResponse = utils.getAuthResponse(req, this.authMethodId); const userProfile = authResponse.profile; debug('/authorize/login: Calling authorization end point.'); debug(userProfile); const scope = GenericOAuth2Router.mergeUserGroupScope(authRequest.scope, authResponse.groups); oauth2.authorize({ response_type: authRequest.response_type, authenticated_userid: this.makeAuthenticatedUserId(authRequest, authResponse), api_id: authRequest.api_id, client_id: authRequest.client_id, redirect_uri: authRequest.redirect_uri, scope: scope, auth_method: req.app.get('server_name') + ':' + this.authMethodId, }, function (err, redirectUri) { debug('/authorize/login: Authorization end point returned.'); if (err) return failError(400, err, next); if (!redirectUri.redirect_uri) return failMessage(500, 'Server error, no redirect URI returned.', next); let uri = redirectUri.redirect_uri; // In the PKCE case, also associate the code_challenge and code_challenge_method with // the profile, as we need to verify those when getting the token. These may both be // null, but that is okay. userProfile.code_challenge = authRequest.code_challenge; userProfile.code_challenge_method = authRequest.code_challenge_method; // This is also a small hack to remember whether we need to send the scopes with the // access token response (because the scope has changed to what was requested). userProfile.scope_differs = authRequest.scope_differs; // For this redirect_uri, which can contain either a code or an access token, // associate the profile (userInfo). profileStore.registerTokenOrCode(redirectUri, authRequest.api_id, userProfile, function (err) { if (err) return failError(500, err, next); // IMPLICIT GRANT ONLY if (authRequest.response_type == 'token' && authRequest.scope_differs) uri += '&scope=' + qs.escape(scope.join(' ')); if (authRequest.state) uri += '&state=' + qs.escape(authRequest.state); if (authRequest.namespace) uri += '&namespace=' + qs.escape(authRequest.namespace); return res.redirect(uri); }); }); } private authorizeByUserPassAsync = async (username: string, password: string): Promise<AuthResponse> => { const instance = this; return new Promise<AuthResponse>(function (resolve, reject) { instance.idp.authorizeByUserPass(username, password, (err, authResponse: AuthResponse) => { err ? reject(err) : resolve(authResponse); }); }); } private async tokenPasswordGrant(tokenRequest: TokenRequest): Promise<AccessToken> { debug('tokenPasswordGrant()'); const instance = this; // Let's validate the subscription first... const subscriptionInfo = await utilsOAuth2.validateSubscription(tokenRequest); const trustedSubscription = subscriptionInfo.subscription.trusted; if (subscriptionInfo.application.confidential) { // Also check client_secret here if (!tokenRequest.client_secret) throw makeOAuthError(401, 'invalid_request', 'A confidential application must also pass its client_secret'); if (subscriptionInfo.subscription.clientSecret !== tokenRequest.client_secret) throw makeOAuthError(401, 'invalid_request', 'Invalid client secret'); } // Retrieve API information let apiInfo: WickedApi; try { apiInfo = await utils.getApiInfoAsync(tokenRequest.api_id); } catch (err) { error(err); throw makeOAuthError(err.statusCode, 'server_error', 'could not retrieve API information'); } // Now we know whether we have a trusted subscription or not; only allow trusted subscriptions to // retrieve a token via the password grant. The only exception is when using passthrough scopes, where // the scope is calculated via a lookup to a 3rd party service anyway. if (!trustedSubscription && !apiInfo.passthroughScopeUrl) throw makeOAuthError(400, 'invalid_request', 'only trusted application subscriptions can retrieve tokens via the password grant.'); const validatedScopes = await utilsOAuth2.validateApiScopes(tokenRequest.api_id, tokenRequest.scope, subscriptionInfo); // Update the scopes tokenRequest.scope = validatedScopes.validatedScopes; tokenRequest.scope_differs = validatedScopes.scopeDiffers; let authResponse: AuthResponse = null; try { authResponse = await instance.authorizeByUserPassAsync(tokenRequest.username, tokenRequest.password); } catch (err) { // Don't answer wrong logins immediately please. // TODO: The error message must be IdP specific, can be some other type // of error than just wrong username or password. let code = 'invalid_request'; let msg = 'Invalid username or password.'; if (err.message) msg += ' ' + err.message; await utils.delay(500); throw makeOAuthError(err.statusCode, code, msg); } // TODO: In the LDAP case, the ROPG may work even if the user has not logged // in and thus does not yet have a user in the wicked database; this user has to // be created on the fly here, and possibly also needs a registration done // automatically, if the API needs a registration. If not, it's fine as is, but // the user needs a dedicated wicked local user (with a "sub" == user id) try { authResponse = await instance.checkUserFromAuthResponseAsync(authResponse, tokenRequest.api_id); } catch (err) { // TODO: Rethink error messages and such. await utils.delay(500); throw makeOAuthError(err.statusCode, 'invalid_request', 'could not verify user in auth response'); } // Now we want to check the registration status of this user with respect to // the API; in case the API does not have a registration pool set, we're done. // If it does, we have to distinguish the two cases "requires namespace" or // "does not require namespace". In case there is no namespace required, the // user *must* have a registration for the pool for this to succeed. In case // the pool requires a namespace, the request will still succeed even if there // aren't any registrations, but the list of associated namespaces is empty. // The created authenticated_userid is also differing depending on the case. // We must do the switch-case here again regarding passthrough users and passthrough scopes... // Check for passthrough scopes and users if (apiInfo.passthroughUsers && !apiInfo.passthroughScopeUrl) { throw makeOAuthError(500, 'server_error', 'when using the combination of passthrough users and not retrieving the scope from a third party, password grant cannot be used.'); } else if (!apiInfo.passthroughUsers && apiInfo.passthroughScopeUrl) { // wicked manages the users, but scope is calculated by somebody else throw makeOAuthError(500, 'server_error', 'wicked managed users and passthrough scope URL is not yet implemented (spec unclear).'); } else if (apiInfo.passthroughUsers && apiInfo.passthroughScopeUrl) { // Passthrough users and passthrough scopes try { const passthroughScopes = await instance.resolvePassthroughScopeAsync(tokenRequest.scope, authResponse.defaultProfile, apiInfo.passthroughScopeUrl); if (!passthroughScopes.allow) { let msg = 'Scope validation with external system disallowed login (property "allow" is not present or not set to true)'; if (passthroughScopes.error_message) msg += `: ${passthroughScopes.error_message}`; throw makeOAuthError(403, msg, 'could not resolve passthrough API scopes from 3rd party'); } tokenRequest.scope = passthroughScopes.authenticated_scope || []; tokenRequest.authenticated_userid = passthroughScopes.authenticated_userid; tokenRequest.authenticated_userid_is_verbose = true; } catch (err) { error(err); throw makeOAuthError(err.status || 500, 'server_error', err.oauthError || 'could not resolve passthrough API scopes from 3rd party'); } } // else: wicked backed users and scopes managed by wicked; standard case. tokenRequest.scope = GenericOAuth2Router.mergeUserGroupScope(tokenRequest.scope, authResponse.groups); // Does this API have a registration pool at all? if (!apiInfo.registrationPool) { // No, this is fine. Now check if we can issue a token. tokenRequest.authenticated_userid = tokenRequest.authenticated_userid || `sub=${authResponse.userId}`; tokenRequest.session_data = authResponse.profile; return await oauth2.tokenAsync(tokenRequest); } // Combination of passthrough users and registration pools? Not possible. if (apiInfo.passthroughUsers) { throw makeOAuthError(500, 'server_error', 'registration pools cannot be combined with passthrough users (wicked needs to store data on the users)'); } // OK, we have a registration pool, let's investigate further. let poolInfo = null; try { poolInfo = await utils.getPoolInfoAsync(apiInfo.registrationPool); } catch (err) { throw makeOAuthError(err.statusCode, 'server_error', 'could not retrieve registration pool information'); } // Then let's also retrieve the registrations for this user debug(`tokenPasswordGrant: Get user registrations for user ${authResponse.userId} and pool ${poolInfo.id}`) let userRegs; try { userRegs = await wicked.getUserRegistrations(poolInfo.id, authResponse.userId); } catch (err) { throw makeOAuthError(err.statusCode, 'server_error', 'could not retrieve user registrations'); } // Case 1: No namespace required if (!poolInfo.requiresNamespace) { debug('tokenPasswordGrant: No namespace required, checking for registrations.'); // Just check whether we have a registration if (userRegs.items.length <= 0) { // Naw, not good. throw makeOAuthError(403, 'access_denied', 'accessing this API requires an existing user registration'); } // OK, we're fine. debug('tokenPasswordGrant: Success so far, issuing token.'); tokenRequest.authenticated_userid = `sub=${authResponse.userId}`; tokenRequest.session_data = authResponse.profile; return await oauth2.tokenAsync(tokenRequest); } else { // Case 2: Namespace required // Here we change the authenticated_userid slightly to carry both the sub and namespace information let authenticatedUserId = `sub=${authResponse.userId};namespaces=`; let first = true; for (let i = 0; i < userRegs.items.length; ++i) { if (!first) authenticatedUserId += ','; authenticatedUserId += userRegs.items[i].namespace; first = false; } debug(`tokenPasswordGrant: Namespace required; authenticated_userid=${authenticatedUserId}`) debug('tokenPasswordGrant: Success so far, issuing token.'); tokenRequest.authenticated_userid = authenticatedUserId; tokenRequest.session_data = authResponse.profile; return await oauth2.tokenAsync(tokenRequest); } } private checkUserFromAuthResponseAsync = async (authResponse: AuthResponse, apiId: string): Promise<AuthResponse> => { debug(`checkUserFromAuthResponse(..., ${apiId})`); const instance = this; const apiInfo = await utils.getApiInfoAsync(apiId); if (apiInfo.passthroughUsers) { // The API doesn't need persisted users, so we are done here now. debug(`checkUserFromAuthResponse: Passthrough API ${apiId}`); authResponse.userId = null; authResponse.groups = []; return authResponse; } // The Auth response contains the default profile, which may or may not // match the stored profile in the wicked database. Plus that we might need to // create a federated user record in case we have a good valid 3rd party user, // which we want to track in the user database of wicked. async function loadWickedUser(userId) { debug(`loadWickedUser(${userId})`); const userInfo = await wicked.getUser(userId); debug('loadUserAndProfile returned.'); // This just fills userId. // The rest is done when handling the registrations (see // registrationFlow()). const oidcProfile = utilsOAuth2.wickedUserInfoToOidcProfile(userInfo) as OidcProfile; authResponse.userId = userId; authResponse.profile = oidcProfile; authResponse.groups = userInfo.groups; return authResponse; } if (authResponse.userId) { // We already have a wicked user id, load the user and fill the profile return loadWickedUser(authResponse.userId); } else if (authResponse.customId) { // Let's check the custom ID, load by custom ID const shortInfo = await utils.getUserByCustomId(authResponse.customId); if (!shortInfo) { // Not found, we must create first await instance.createUserFromDefaultProfile(authResponse); return loadWickedUser(authResponse.userId); } else { await instance.checkDefaultGroups(shortInfo, authResponse); return loadWickedUser(shortInfo.id); } } else { throw new Error('checkUserFromAuthResponse: Neither customId nor userId was passed into authResponse.'); } } // Takes an authResponse, returns an authResponse private createUserFromDefaultProfile = async (authResponse: AuthResponse): Promise<AuthResponse> => { debug('createUserFromDefaultProfile()'); const instance = this; // The defaultProfile MUST contain an email address. // The id of the new user is created by the API and returned here; // This is still an incognito user, name and such are amended later // in the process, via the registration. const userCreateInfo: WickedUserCreateInfo = { customId: authResponse.customId, email: authResponse.defaultProfile.email, validated: authResponse.defaultProfile.email_verified, groups: authResponse.defaultGroups }; try { const userInfo = await wicked.createUser(userCreateInfo) as WickedUserInfo; debug(`createUserFromDefaultProfile: Created new user with id ${userInfo.id}`); authResponse.userId = userInfo.id; // Check whether we need to create a verification request, in case the email // address is not yet verified by the federated IdP (can happen with Twitter). // That we do asynchronously and return immediately without waiting for that. if (!userCreateInfo.validated) { info(`Creating email verification request for email ${userCreateInfo.email}...`); utils.createVerificationRequest(false, instance.authMethodId, userCreateInfo.email, (err) => { if (err) { error(`Creating email verification request for email ${userCreateInfo.email} failed`); error(err); return; } info(`Created email verification request for email ${userCreateInfo.email} successfully`); return; }); } return authResponse; } catch (err) { error('createUserFromDefaultProfile: POST to /users failed.'); error(err); // Check if it's a 409, and if so, display a nicer error message. if (err.status === 409 || err.statusCode === 409) throw makeError(`A user with the email address "${userCreateInfo.email}" already exists in the system. Please log in using the existing user's identity.`, 409); throw err; } } private checkDefaultGroups = async (shortInfo: WickedUserShortInfo, authResponse: AuthResponse): Promise<any> => { debug(`checkDefaultGroups()`); if (!authResponse.defaultGroups) return null; try { const userInfo = await wicked.getUser(shortInfo.id); if (!userInfo.groups) userInfo.groups = []; // Compare groups and default groups let needsUpdate = false; for (let i = 0; i < authResponse.defaultGroups.length; ++i) { const defGroup = authResponse.defaultGroups[i]; if (!userInfo.groups.find(g => g == defGroup)) { userInfo.groups.push(defGroup); needsUpdate = true; } } if (needsUpdate) { debug(`checkDefaultGroups(): Updated groups to ${userInfo.groups.join(', ')}`); await wicked.patchUser(shortInfo.id, userInfo); } return null; } catch (err) { // Just log the error; this is not good, but should not prevent logging in. error(`checkDefaultGroups(): Checking default groups failed for user with id ${shortInfo.id} (email ${shortInfo.email}).`); error(err); return null; } } private static extractUserId(authUserId: string): string { if (!authUserId.startsWith('sub=')) return authUserId; // Does it look like this: "sub=<user id>;namespace=<whatever>" const semicolonIndex = authUserId.indexOf(';'); if (semicolonIndex < 0) { // We have only sub=<userid>, no namespace return authUserId.substring(4); } return authUserId.substring(4, semicolonIndex); } private static cleanupScopeString(scopes: string): string[] { debug(`cleanupScopeString(${scopes})`); if (!scopes) return []; const scopeList = scopes.split(' '); return scopeList.filter(s => !s.startsWith('wicked:') && s.trim()); } private checkRefreshTokenAsync = async (tokenInfo, apiInfo: WickedApi): Promise<CheckRefreshDecision> => { const instance = this; return new Promise<CheckRefreshDecision>(function (resolve, reject) { instance.idp.checkRefreshToken(tokenInfo, apiInfo, function (err, data) { err ? reject(err) : resolve(data); }); }); } private tokenRefreshToken = async (tokenRequest: TokenRequest): Promise<AccessToken> => { debug('tokenRefreshToken()'); const instance = this; // Client validation and all that stuff can be done in the OAuth2 adapter, // but we still need to verify that the user for which the refresh token was // created is still a valid user. const refreshToken = tokenRequest.refresh_token; let tokenInfo: TokenInfo; try { tokenInfo = await tokens.getTokenDataByRefreshTokenAsync(refreshToken); } catch (err) { throw makeOAuthError(400, 'invalid_request', 'could not retrieve information on the given refresh token.', err); } debug('refresh token info:'); debug(tokenInfo); let apiInfo: WickedApi; let applicationId: string; try { const credentialInfo = await kongUtils.lookupApiAndApplicationFromKongCredentialAsync(tokenInfo.credential_id); apiInfo = await utils.getApiInfoAsync(credentialInfo.apiId); applicationId = credentialInfo.applicationId; } catch (err) { throw makeOAuthError(500, 'server_error', 'could not lookup API from given refresh token.', err); } // Check for passthrough scopes and users if (apiInfo.passthroughUsers && !apiInfo.passthroughScopeUrl) { throw makeOAuthError(500, 'server_error', 'when using the combination of passthrough users and not retrieving the scope from a third party, refresh tokens cannot be used.'); } else if (!apiInfo.passthroughUsers && apiInfo.passthroughScopeUrl) { // wicked manages the users, but scope is calculated by somebody else throw makeOAuthError(500, 'server_error', 'wicked managed users and passthrough scope URL is not yet implemented (spec unclear).'); } else if (!apiInfo.passthroughUsers && !apiInfo.passthroughScopeUrl) { // Normal case const userId = GenericOAuth2Router.extractUserId(tokenInfo.authenticated_userid); if (!userId) throw makeOAuthError(500, 'server_error', 'could not correctly retrieve authenticated user id from refresh token'); let refreshCheckResult: CheckRefreshDecision; try { refreshCheckResult = await instance.checkRefreshTokenAsync(tokenInfo, apiInfo); } catch (err) { throw makeOAuthError(500, 'server_error', 'checking the refresh token returned an unexpected error.', err); } if (!refreshCheckResult.allowRefresh) throw makeOAuthError(403, 'server_error', 'idp disallowed refreshing the token'); let userInfo: WickedUserInfo; try { userInfo = await wicked.getUser(userId); } catch (err) { throw makeOAuthError(400, 'invalid_request', 'user associated with refresh token is not a valid user (anymore)', err); } debug('wicked local user info:'); debug(userInfo); let subscriptionInfo: WickedSubscription; try { subscriptionInfo = await wicked.getSubscription(applicationId, apiInfo.id); } catch (err) { throw makeOAuthError(403, 'unauthorized_client', 'Could not load application subscription to API', err); } // If the subscription is trusted, we don't need this check if (!subscriptionInfo.trusted) { // Make sure we still have the desired scope granted to the application const tokenScope = GenericOAuth2Router.cleanupScopeString(tokenInfo.scope); if (tokenScope.length > 0) { // Handles 404 const userGrant = await utils.getUserGrantAsync(userId, applicationId, apiInfo.id); const missingGrants = instance.diffGrants(userGrant.grants, tokenScope); if (missingGrants.length > 0) { warn(`tokenRefreshToken: Attempt to refresh a token for which there is no grant (anymore)`); warn(`tokenRefreshToken: Missing grants: ${missingGrants.toString()}`); throw makeOAuthError(403, 'unauthorized_client', 'Application tried to refresh a token with a certain scope, but scope is not granted by resource owner.'); } // Now also check allowed scopes; this *might* have changed if (subscriptionInfo.allowedScopesMode === WickedSubscriptionScopeModeType.None) { warn(`tokenRefreshToken: Application ${applicationId} has scope mode set to "none", denying refresh of token which has a scope`); throw makeOAuthError(403, 'unauthorized_client', 'Application tried to refresh a token with a non-empty scope, but is not allowed any scopes.'); } // "Select" Mode - only specific scope allowed if (subscriptionInfo.allowedScopesMode === WickedSubscriptionScopeModeType.Select) { for (let i = 0; i < tokenScope.length; ++i) { if (!subscriptionInfo.allowedScopes.find(s => s == tokenScope[i])) throw makeOAuthError(403, 'unauthorized_client', `Application tried refresh a token with scope "${tokenScope[i]}", but this scope is not allowed.`); } } // Else case: "All", any scope is allowed for the application/subscription } } const oidcProfile = utilsOAuth2.wickedUserInfoToOidcProfile(userInfo); tokenRequest.session_data = oidcProfile; // Now delegate to oauth2 adapter: return await oauth2.tokenAsync(tokenRequest); } else { // Passthrough users and passthrough scope URL, the other usual case if the user // is not the resource owner. Ask third party. const tempProfile: OidcProfile = { sub: tokenInfo.authenticated_userid }; let refreshCheckResult: CheckRefreshDecision; try { refreshCheckResult = await instance.checkRefreshTokenAsync(tokenInfo, apiInfo); } catch (err) { throw makeOAuthError(500, 'server_error', 'checking whether refresh is allowed return an unexpected error', err); } if (!refreshCheckResult.allowRefresh) throw makeOAuthError(403, 'server_error', 'idp disallowed refreshing the token'); const scopes = GenericOAuth2Router.cleanupScopeString(tokenInfo.scope); let scopeResponse: PassthroughScopeResponse; try { scopeResponse = await instance.resolvePassthroughScopeAsync(scopes, tempProfile, apiInfo.passthroughScopeUrl); } catch (err) { throw makeOAuthError(500, 'server_error', 'Could not resolve passthrough scope via external service.', err); } tokenRequest.session_data = tempProfile; // HACK_PASSTHROUGH_REFRESH: We will have to rewrite this to a "password" grant, as we cannot change the scope otherwise tokenRequest.grant_type = 'password'; tokenRequest.authenticated_userid = scopeResponse.authenticated_userid; tokenRequest.authenticated_userid_is_verbose = true; tokenRequest.scope = scopeResponse.authenticated_scope; // Tell tokenPasswordGrantKong that it's okay to use the password grant even if the API is not // configured to support it. tokenRequest.accept_password_grant = true; // If this throws, it falls through (on purpose) const accessToken = await oauth2.tokenAsync(tokenRequest); // Delete the old token; this is async, on purpose, we just log // errors but don't fail if this actually fails. tokens.deleteTokens(tokenInfo.access_token, null, (err) => { if (err) error(err); }); return accessToken; } } }
the_stack
import nodePath from 'path'; import { getOrCreateModel, pagePathUtils, pathUtils } from '@growi/core'; import escapeStringRegexp from 'escape-string-regexp'; import mongoose, { Schema, Model, Document, AnyObject, } from 'mongoose'; import mongoosePaginate from 'mongoose-paginate-v2'; import uniqueValidator from 'mongoose-unique-validator'; import { IPage, IPageHasId, PageGrant } from '~/interfaces/page'; import { IUserHasId } from '~/interfaces/user'; import { ObjectIdLike } from '~/server/interfaces/mongoose-utils'; import loggerFactory from '../../utils/logger'; import Crowi from '../crowi'; import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page'; const { addTrailingSlash, normalizePath } = pathUtils; const { isTopPage, collectAncestorPaths, hasSlash, } = pagePathUtils; const logger = loggerFactory('growi:models:page'); /* * define schema */ const GRANT_PUBLIC = 1; const GRANT_RESTRICTED = 2; const GRANT_SPECIFIED = 3; // DEPRECATED const GRANT_OWNER = 4; const GRANT_USER_GROUP = 5; const PAGE_GRANT_ERROR = 1; const STATUS_PUBLISHED = 'published'; const STATUS_DELETED = 'deleted'; export interface PageDocument extends IPage, Document { [x:string]: any // for obsolete methods } type TargetAndAncestorsResult = { targetAndAncestors: PageDocument[] rootPage: PageDocument } type PaginatedPages = { pages: PageDocument[], totalCount: number, limit: number, offset: number } export type CreateMethod = (path: string, body: string, user, options: PageCreateOptions) => Promise<PageDocument & { _id: any }> export interface PageModel extends Model<PageDocument> { [x: string]: any; // for obsolete static methods findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument | PageDocument[] | null> findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult> findRecentUpdatedPages(path: string, user, option, includeEmpty?: boolean): Promise<PaginatedPages> generateGrantCondition( user, userGroups, showAnyoneKnowsLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean, ): { $or: any[] } PageQueryBuilder: typeof PageQueryBuilder GRANT_PUBLIC GRANT_RESTRICTED GRANT_SPECIFIED GRANT_OWNER GRANT_USER_GROUP PAGE_GRANT_ERROR STATUS_PUBLISHED STATUS_DELETED } type IObjectId = mongoose.Types.ObjectId; const ObjectId = mongoose.Schema.Types.ObjectId; const schema = new Schema<PageDocument, PageModel>({ parent: { type: ObjectId, ref: 'Page', index: true, default: null, }, descendantCount: { type: Number, default: 0 }, isEmpty: { type: Boolean, default: false }, path: { type: String, required: true, index: true, }, revision: { type: ObjectId, ref: 'Revision' }, status: { type: String, default: STATUS_PUBLISHED, index: true }, grant: { type: Number, default: GRANT_PUBLIC, index: true }, grantedUsers: [{ type: ObjectId, ref: 'User' }], grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true }, creator: { type: ObjectId, ref: 'User', index: true }, lastUpdateUser: { type: ObjectId, ref: 'User' }, liker: [{ type: ObjectId, ref: 'User' }], seenUsers: [{ type: ObjectId, ref: 'User' }], commentCount: { type: Number, default: 0 }, pageIdOnHackmd: { type: String }, revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified updatedAt: { type: Date, default: Date.now }, // Do not use timetamps for updatedAt because it breaks 'updateMetadata: false' option deleteUser: { type: ObjectId, ref: 'User' }, deletedAt: { type: Date }, }, { timestamps: { createdAt: true, updatedAt: false }, toJSON: { getters: true }, toObject: { getters: true }, }); // apply plugins schema.plugin(mongoosePaginate); schema.plugin(uniqueValidator); export class PageQueryBuilder { query: any; constructor(query, includeEmpty = false) { this.query = query; if (!includeEmpty) { this.query = this.query .and({ $or: [ { isEmpty: false }, { isEmpty: null }, // for v4 compatibility ], }); } } /** * Used for filtering the pages at specified paths not to include unintentional pages. * @param pathsToFilter The paths to have additional filters as to be applicable * @returns PageQueryBuilder */ addConditionToFilterByApplicableAncestors(pathsToFilter: string[]) { this.query = this.query .and( { $or: [ { path: '/' }, { path: { $in: pathsToFilter }, grant: GRANT_PUBLIC, status: STATUS_PUBLISHED }, { path: { $in: pathsToFilter }, parent: { $ne: null }, status: STATUS_PUBLISHED }, { path: { $nin: pathsToFilter }, status: STATUS_PUBLISHED }, ], }, ); return this; } addConditionToExcludeTrashed() { this.query = this.query .and({ $or: [ { status: null }, { status: STATUS_PUBLISHED }, ], }); return this; } /** * generate the query to find the pages '{path}/*' and '{path}' self. * If top page, return without doing anything. */ addConditionToListWithDescendants(path: string, option?) { // No request is set for the top page if (isTopPage(path)) { return this; } const pathNormalized = pathUtils.normalizePath(path); const pathWithTrailingSlash = addTrailingSlash(path); const startsPattern = escapeStringRegexp(pathWithTrailingSlash); this.query = this.query .and({ $or: [ { path: pathNormalized }, { path: new RegExp(`^${startsPattern}`) }, ], }); return this; } /** * generate the query to find the pages '{path}/*' (exclude '{path}' self). * If top page, return without doing anything. */ addConditionToListOnlyDescendants(path, option) { // No request is set for the top page if (isTopPage(path)) { return this; } const pathWithTrailingSlash = addTrailingSlash(path); const startsPattern = escapeStringRegexp(pathWithTrailingSlash); this.query = this.query .and({ path: new RegExp(`^${startsPattern}`) }); return this; } addConditionToListOnlyAncestors(path) { const pathNormalized = pathUtils.normalizePath(path); const ancestorsPaths = extractToAncestorsPaths(pathNormalized); this.query = this.query .and({ path: { $in: ancestorsPaths, }, }); return this; } /** * generate the query to find pages that start with `path` * * In normal case, returns '{path}/*' and '{path}' self. * If top page, return without doing anything. * * *option* * Left for backward compatibility */ addConditionToListByStartWith(str: string): PageQueryBuilder { const path = normalizePath(str); // No request is set for the top page if (isTopPage(path)) { return this; } const startsPattern = escapeStringRegexp(path); this.query = this.query .and({ path: new RegExp(`^${startsPattern}`) }); return this; } addConditionToListByNotStartWith(str: string): PageQueryBuilder { const path = normalizePath(str); // No request is set for the top page if (isTopPage(path)) { return this; } const startsPattern = escapeStringRegexp(str); this.query = this.query .and({ path: new RegExp(`^(?!${startsPattern}).*$`) }); return this; } addConditionToListByMatch(str: string): PageQueryBuilder { // No request is set for "/" if (str === '/') { return this; } const match = escapeStringRegexp(str); this.query = this.query .and({ path: new RegExp(`^(?=.*${match}).*$`) }); return this; } addConditionToListByNotMatch(str: string): PageQueryBuilder { // No request is set for "/" if (str === '/') { return this; } const match = escapeStringRegexp(str); this.query = this.query .and({ path: new RegExp(`^(?!.*${match}).*$`) }); return this; } async addConditionForParentNormalization(user) { // determine UserGroup condition let userGroups; if (user != null) { const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user); } const grantConditions: any[] = [ { grant: null }, { grant: GRANT_PUBLIC }, ]; if (user != null) { grantConditions.push( { grant: GRANT_OWNER, grantedUsers: user._id }, ); } if (userGroups != null && userGroups.length > 0) { grantConditions.push( { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } }, ); } this.query = this.query .and({ $or: grantConditions, }); return this; } async addConditionAsMigratablePages(user) { this.query = this.query .and({ $or: [ { grant: { $ne: GRANT_RESTRICTED } }, { grant: { $ne: GRANT_SPECIFIED } }, ], }); this.addConditionAsNotMigrated(); this.addConditionAsNonRootPage(); this.addConditionToExcludeTrashed(); await this.addConditionForParentNormalization(user); return this; } // add viewer condition to PageQueryBuilder instance async addViewerCondition(user, userGroups = null): Promise<PageQueryBuilder> { let relatedUserGroups = userGroups; if (user != null && relatedUserGroups == null) { const UserGroupRelation: any = mongoose.model('UserGroupRelation'); relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user); } this.addConditionToFilteringByViewer(user, relatedUserGroups, false); return this; } addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) { const condition = generateGrantCondition(user, userGroups, showAnyoneKnowsLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup); this.query = this.query .and(condition); return this; } addConditionToPagenate(offset, limit, sortOpt?) { this.query = this.query .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call return this; } addConditionAsNonRootPage() { this.query = this.query.and({ path: { $ne: '/' } }); return this; } addConditionAsNotMigrated() { this.query = this.query .and({ parent: null }); return this; } addConditionAsOnTree() { this.query = this.query .and( { $or: [ { parent: { $ne: null } }, { path: '/' }, ], }, ); return this; } /* * Add this condition when get any ancestor pages including the target's parent */ addConditionToSortPagesByDescPath() { this.query = this.query.sort('-path'); return this; } addConditionToSortPagesByAscPath() { this.query = this.query.sort('path'); return this; } addConditionToMinimizeDataForRendering() { this.query = this.query.select('_id path isEmpty grant revision descendantCount'); return this; } addConditionToListByPathsArray(paths) { this.query = this.query .and({ path: { $in: paths, }, }); return this; } addConditionToListByPageIdsArray(pageIds) { this.query = this.query .and({ _id: { $in: pageIds, }, }); return this; } addConditionToExcludeByPageIdsArray(pageIds) { this.query = this.query .and({ _id: { $nin: pageIds, }, }); return this; } populateDataToList(userPublicFields) { this.query = this.query .populate({ path: 'lastUpdateUser', select: userPublicFields, }); return this; } populateDataToShowRevision(userPublicFields) { this.query = populateDataToShowRevision(this.query, userPublicFields); return this; } addConditionToFilteringByParentId(parentId) { this.query = this.query.and({ parent: parentId }); return this; } } schema.statics.createEmptyPage = async function( path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506 ): Promise<PageDocument & { _id: any }> { if (parent == null) { throw Error('parent must not be null'); } const Page = this; const page = new Page(); page.path = path; page.isEmpty = true; page.parent = parent; page.descendantCount = descendantCount; return page.save(); }; /** * Replace an existing page with an empty page. * It updates the children's parent to the new empty page's _id. * @param exPage a page document to be replaced * @returns Promise<void> */ schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) { // find parent const parent = await this.findOne({ _id: exPage.parent }); if (parent == null) { throw Error('parent to update does not exist. Prepare parent first.'); } // create empty page at path const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith; // find children by ex-page _id const children = await this.find({ parent: exPage._id }); // bulkWrite const operationForNewTarget = { updateOne: { filter: { _id: newTarget._id }, update: { parent: parent._id, }, }, }; const operationsForChildren = { updateMany: { filter: { _id: { $in: children.map(d => d._id) }, }, update: { parent: newTarget._id, }, }, }; await this.bulkWrite([operationForNewTarget, operationsForChildren]); const isExPageEmpty = exPage.isEmpty; if (deleteExPageIfEmpty && isExPageEmpty) { await this.deleteOne({ _id: exPage._id }); logger.warn('Deleted empty page since it was replaced with another page.'); } return this.findById(newTarget._id); }; /* * Find pages by ID and viewer. */ schema.statics.findByIdsAndViewer = async function(pageIds: string[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> { const baseQuery = this.find({ _id: { $in: pageIds } }); const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty); await queryBuilder.addViewerCondition(user, userGroups); return queryBuilder.query.exec(); }; /* * Find a page by path and viewer. Pass false to useFindOne to use findOne method. */ schema.statics.findByPathAndViewer = async function( path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false, ): Promise<PageDocument | PageDocument[] | null> { if (path == null) { throw new Error('path is required.'); } const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path }); const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty); await queryBuilder.addViewerCondition(user, userGroups); return queryBuilder.query.exec(); }; schema.statics.findRecentUpdatedPages = async function( path: string, user, options, includeEmpty = false, ): Promise<PaginatedPages> { const sortOpt = {}; sortOpt[options.sort] = options.desc; const Page = this; const User = mongoose.model('User') as any; if (path == null) { throw new Error('path is required.'); } const baseQuery = this.find({}); const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty); if (!options.includeTrashed) { queryBuilder.addConditionToExcludeTrashed(); } queryBuilder.addConditionToListWithDescendants(path, options); queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL); await queryBuilder.addViewerCondition(user); const pages = await Page.paginate(queryBuilder.query.clone(), { lean: true, sort: sortOpt, offset: options.offset, limit: options.limit, }); const results = { pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit, }; return results; }; /* * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result * The result will include the target as well */ schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> { let path; if (!hasSlash(pathOrId)) { const _id = pathOrId; const page = await this.findOne({ _id }); path = page == null ? '/' : page.path; } else { path = pathOrId; } const ancestorPaths = collectAncestorPaths(path); ancestorPaths.push(path); // include target // Do not populate const queryBuilder = new PageQueryBuilder(this.find(), true); await queryBuilder.addViewerCondition(user, userGroups); const _targetAndAncestors: PageDocument[] = await queryBuilder .addConditionAsOnTree() .addConditionToListByPathsArray(ancestorPaths) .addConditionToMinimizeDataForRendering() .addConditionToSortPagesByDescPath() .query .lean() .exec(); // no same path pages const ancestorsMap = new Map<string, PageDocument>(); _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page)); const targetAndAncestors = Array.from(ancestorsMap.values()); const rootPage = targetAndAncestors[targetAndAncestors.length - 1]; return { targetAndAncestors, rootPage }; }; /** * Create empty pages at paths at which no pages exist * @param paths Page paths * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths */ schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> { const existingPages = await this.aggregate(aggrPipelineForExistingPages); const existingPagePaths = existingPages.map(page => page.path); const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path)); await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true }))); }; /** * Find a parent page by path * @param {string} path * @returns {Promise<PageDocument | null>} */ schema.statics.findParentByPath = async function(path: string): Promise<PageDocument | null> { const parentPath = nodePath.dirname(path); const builder = new PageQueryBuilder(this.find({ path: parentPath }), true); const pagesCanBeParent = await builder .addConditionAsOnTree() .query .exec(); if (pagesCanBeParent.length >= 1) { return pagesCanBeParent[0]; // the earliest page will be the result } return null; }; /* * Utils from obsolete-page.js */ export async function pushRevision(pageData, newRevision, user) { await newRevision.save(); pageData.revision = newRevision; pageData.lastUpdateUser = user?._id ?? user; pageData.updatedAt = Date.now(); return pageData.save(); } /** * add/subtract descendantCount of pages with provided paths by increment. * increment can be negative number */ schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> { await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } }); }; /** * recount descendantCount of a page with the provided id and return it */ schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> { const res = await this.aggregate( [ { $match: { parent: id, }, }, { $project: { parent: 1, isEmpty: 1, descendantCount: 1, }, }, { $group: { _id: '$parent', sumOfDescendantCount: { $sum: '$descendantCount', }, sumOfDocsCount: { $sum: { $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount }, }, }, }, { $set: { descendantCount: { $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'], }, }, }, ], ); return res.length === 0 ? 0 : res[0].descendantCount; }; schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) { const self = this; const target = await this.findById(pageId); if (target == null) { throw Error('Target not found'); } async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) { const parent = await self.findOne({ _id: target.parent }); if (parent == null) { return ancestors; } return findAncestorsRecursively(parent, [...ancestors, parent]); } return findAncestorsRecursively(target); }; // TODO: write test code /** * Recursively removes empty pages at leaf position. * @param pageId ObjectIdLike * @returns Promise<void> */ schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> { const self = this; const initialPage = await this.findById(pageId); if (initialPage == null) { return; } if (!initialPage.isEmpty) { return; } async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> { if (!page.isEmpty) { return pageIds; } const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id }); if (isChildrenOtherThanTargetExist) { return pageIds; } pageIds.push(page._id); const nextPage = await self.findById(page.parent); if (nextPage == null) { return pageIds; } return generatePageIdsToRemove(page, nextPage, pageIds); } const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage); await this.deleteMany({ _id: { $in: pageIdsToRemove } }); }; schema.statics.normalizeDescendantCountById = async function(pageId) { const children = await this.find({ parent: pageId }); const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2); const sumChildPages = children.filter(p => !p.isEmpty).length; return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true }); }; schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) { return this.findByIdAndUpdate(pageId, { $set: { parent: null } }); }; schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> { await this.deleteMany({ _id: { $nin: pageIdsToNotRemove, }, path: { $in: paths, }, isEmpty: true, }); }; /** * Find a not empty parent recursively. * @param {string} path * @returns {Promise<PageDocument | null>} */ schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> { const parent = await this.findParentByPath(path); if (parent == null) { return null; } const recursive = async(page: PageDocument): Promise<PageDocument> => { if (!page.isEmpty) { return page; } const next = await this.findById(page.parent); if (next == null || isTopPage(next.path)) { return page; } return recursive(next); }; const notEmptyParent = await recursive(parent); return notEmptyParent; }; schema.statics.findParent = async function(pageId): Promise<PageDocument | null> { return this.findOne({ _id: pageId }); }; schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type export function generateGrantCondition( user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false, ): { $or: any[] } { const grantConditions: AnyObject[] = [ { grant: null }, { grant: GRANT_PUBLIC }, ]; if (showAnyoneKnowsLink) { grantConditions.push({ grant: GRANT_RESTRICTED }); } if (showPagesRestrictedByOwner) { grantConditions.push( { grant: GRANT_SPECIFIED }, { grant: GRANT_OWNER }, ); } else if (user != null) { grantConditions.push( { grant: GRANT_SPECIFIED, grantedUsers: user._id }, { grant: GRANT_OWNER, grantedUsers: user._id }, ); } if (showPagesRestrictedByGroup) { grantConditions.push( { grant: GRANT_USER_GROUP }, ); } else if (userGroups != null && userGroups.length > 0) { grantConditions.push( { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } }, ); } return { $or: grantConditions, }; } schema.statics.generateGrantCondition = generateGrantCondition; export type PageCreateOptions = { format?: string grantUserGroupId?: ObjectIdLike grant?: number } /* * Merge obsolete page model methods and define new methods which depend on crowi instance */ export default (crowi: Crowi): any => { let pageEvent; if (crowi != null) { pageEvent = crowi.event('page'); } const shouldUseUpdatePageV4 = (grant: number, isV5Compatible: boolean, isOnTree: boolean): boolean => { const isRestricted = grant === GRANT_RESTRICTED; return !isRestricted && (!isV5Compatible || !isOnTree); }; schema.statics.emitPageEventUpdate = (page: IPageHasId, user: IUserHasId): void => { pageEvent.emit('update', page, user); }; /** * A wrapper method of schema.statics.updatePage for updating grant only. * @param {PageDocument} page * @param {UserDocument} user * @param options */ schema.statics.updateGrant = async function(page, user, grantData: {grant: PageGrant, grantedGroup: ObjectIdLike}) { const { grant, grantedGroup } = grantData; const options = { grant, grantUserGroupId: grantedGroup, isSyncRevisionToHackmd: false, }; return this.updatePage(page, null, null, user, options); }; schema.statics.updatePage = async function( pageData, body: string | null, previousBody: string | null, user, options: {grant?: PageGrant, grantUserGroupId?: ObjectIdLike, isSyncRevisionToHackmd?: boolean} = {}, ) { if (crowi.configManager == null || crowi.pageGrantService == null || crowi.pageService == null) { throw Error('Crowi is not set up'); } const wasOnTree = pageData.parent != null || isTopPage(pageData.path); const exParent = pageData.parent; const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible'); const shouldUseV4Process = shouldUseUpdatePageV4(pageData.grant, isV5Compatible, wasOnTree); if (shouldUseV4Process) { // v4 compatible process return this.updatePageV4(pageData, body, previousBody, user, options); } const grant = options.grant ?? pageData.grant; // use the previous data if absence const grantUserGroupId: undefined | ObjectIdLike = options.grantUserGroupId ?? pageData.grantedGroup?._id.toString(); const grantedUserIds = pageData.grantedUserIds || [user._id]; const shouldBeOnTree = grant !== GRANT_RESTRICTED; const isChildrenExist = await this.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(pageData.path))}`), parent: { $ne: null } }); const newPageData = pageData; if (shouldBeOnTree) { let isGrantNormalized = false; try { isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(user, pageData.path, grant, grantedUserIds, grantUserGroupId, true); } catch (err) { logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err); throw err; } if (!isGrantNormalized) { throw Error('The selected grant or grantedGroup is not assignable to this page.'); } if (!wasOnTree) { const newParent = await crowi.pageService.getParentAndFillAncestorsByUser(user, newPageData.path); newPageData.parent = newParent._id; } } else { if (wasOnTree && isChildrenExist) { // Update children's parent with new parent const newParentForChildren = await this.createEmptyPage(pageData.path, pageData.parent, pageData.descendantCount); await this.updateMany( { parent: pageData._id }, { parent: newParentForChildren._id }, ); } newPageData.parent = null; newPageData.descendantCount = 0; } newPageData.applyScope(user, grant, grantUserGroupId); // update existing page let savedPage = await newPageData.save(); // Update body const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd; const isBodyPresent = body != null && previousBody != null; const shouldUpdateBody = isBodyPresent; if (shouldUpdateBody) { const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user); savedPage = await pushRevision(savedPage, newRevision, user); await savedPage.populateDataToShowRevision(); if (isSyncRevisionToHackmd) { savedPage = await this.syncRevisionToHackmd(savedPage); } } this.emitPageEventUpdate(savedPage, user); // Update ex children's parent if (!wasOnTree && shouldBeOnTree) { const emptyPageAtSamePath = await this.findOne({ path: pageData.path, isEmpty: true }); // this page is necessary to find children if (isChildrenExist) { if (emptyPageAtSamePath != null) { // Update children's parent with new parent await this.updateMany( { parent: emptyPageAtSamePath._id }, { parent: savedPage._id }, ); } } await this.findOneAndDelete({ path: pageData.path, isEmpty: true }); // delete here } // Sub operation // 1. Update descendantCount const shouldPlusDescCount = !wasOnTree && shouldBeOnTree; const shouldMinusDescCount = wasOnTree && !shouldBeOnTree; if (shouldPlusDescCount) { await crowi.pageService.updateDescendantCountOfAncestors(newPageData._id, 1, false); const newDescendantCount = await this.recountDescendantCount(newPageData._id); await this.updateOne({ _id: newPageData._id }, { descendantCount: newDescendantCount }); } else if (shouldMinusDescCount) { // Update from parent. Parent is null if newPageData.grant is RESTRECTED. if (newPageData.grant === GRANT_RESTRICTED) { await crowi.pageService.updateDescendantCountOfAncestors(exParent, -1, true); } } // 2. Delete unnecessary empty pages const shouldRemoveLeafEmpPages = wasOnTree && !isChildrenExist; if (shouldRemoveLeafEmpPages) { await this.removeLeafEmptyPagesRecursively(exParent); } return savedPage; }; // add old page schema methods const pageSchema = getPageSchema(crowi); schema.methods = { ...pageSchema.methods, ...schema.methods }; schema.statics = { ...pageSchema.statics, ...schema.statics }; return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type };
the_stack
import { ResponseContext, RequestContext, HttpFile } from '../http/http.ts'; import * as models from '../models/all.ts'; import { Configuration} from '../configuration.ts' import { ApiResponse } from '../models/ApiResponse.ts'; import { Category } from '../models/Category.ts'; import { Order } from '../models/Order.ts'; import { Pet } from '../models/Pet.ts'; import { Tag } from '../models/Tag.ts'; import { User } from '../models/User.ts'; import { ObservablePetApi } from "./ObservableAPI.ts"; import { PetApiRequestFactory, PetApiResponseProcessor} from "../apis/PetApi.ts"; export interface PetApiAddPetRequest { /** * Pet object that needs to be added to the store * @type Pet * @memberof PetApiaddPet */ pet: Pet } export interface PetApiDeletePetRequest { /** * Pet id to delete * @type number * @memberof PetApideletePet */ petId: number /** * * @type string * @memberof PetApideletePet */ apiKey?: string } export interface PetApiFindPetsByStatusRequest { /** * Status values that need to be considered for filter * @type Array&lt;&#39;available&#39; | &#39;pending&#39; | &#39;sold&#39;&gt; * @memberof PetApifindPetsByStatus */ status: Array<'available' | 'pending' | 'sold'> } export interface PetApiFindPetsByTagsRequest { /** * Tags to filter by * @type Array&lt;string&gt; * @memberof PetApifindPetsByTags */ tags: Array<string> } export interface PetApiGetPetByIdRequest { /** * ID of pet to return * @type number * @memberof PetApigetPetById */ petId: number } export interface PetApiUpdatePetRequest { /** * Pet object that needs to be added to the store * @type Pet * @memberof PetApiupdatePet */ pet: Pet } export interface PetApiUpdatePetWithFormRequest { /** * ID of pet that needs to be updated * @type number * @memberof PetApiupdatePetWithForm */ petId: number /** * Updated name of the pet * @type string * @memberof PetApiupdatePetWithForm */ name?: string /** * Updated status of the pet * @type string * @memberof PetApiupdatePetWithForm */ status?: string } export interface PetApiUploadFileRequest { /** * ID of pet to update * @type number * @memberof PetApiuploadFile */ petId: number /** * Additional data to pass to server * @type string * @memberof PetApiuploadFile */ additionalMetadata?: string /** * file to upload * @type HttpFile * @memberof PetApiuploadFile */ file?: HttpFile } export class ObjectPetApi { private api: ObservablePetApi public constructor(configuration: Configuration, requestFactory?: PetApiRequestFactory, responseProcessor?: PetApiResponseProcessor) { this.api = new ObservablePetApi(configuration, requestFactory, responseProcessor); } /** * Add a new pet to the store * @param param the request object */ public addPet(param: PetApiAddPetRequest, options?: Configuration): Promise<Pet> { return this.api.addPet(param.pet, options).toPromise(); } /** * Deletes a pet * @param param the request object */ public deletePet(param: PetApiDeletePetRequest, options?: Configuration): Promise<void> { return this.api.deletePet(param.petId, param.apiKey, options).toPromise(); } /** * Multiple status values can be provided with comma separated strings * Finds Pets by status * @param param the request object */ public findPetsByStatus(param: PetApiFindPetsByStatusRequest, options?: Configuration): Promise<Array<Pet>> { return this.api.findPetsByStatus(param.status, options).toPromise(); } /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags * @param param the request object */ public findPetsByTags(param: PetApiFindPetsByTagsRequest, options?: Configuration): Promise<Array<Pet>> { return this.api.findPetsByTags(param.tags, options).toPromise(); } /** * Returns a single pet * Find pet by ID * @param param the request object */ public getPetById(param: PetApiGetPetByIdRequest, options?: Configuration): Promise<Pet> { return this.api.getPetById(param.petId, options).toPromise(); } /** * Update an existing pet * @param param the request object */ public updatePet(param: PetApiUpdatePetRequest, options?: Configuration): Promise<Pet> { return this.api.updatePet(param.pet, options).toPromise(); } /** * Updates a pet in the store with form data * @param param the request object */ public updatePetWithForm(param: PetApiUpdatePetWithFormRequest, options?: Configuration): Promise<void> { return this.api.updatePetWithForm(param.petId, param.name, param.status, options).toPromise(); } /** * uploads an image * @param param the request object */ public uploadFile(param: PetApiUploadFileRequest, options?: Configuration): Promise<ApiResponse> { return this.api.uploadFile(param.petId, param.additionalMetadata, param.file, options).toPromise(); } } import { ObservableStoreApi } from "./ObservableAPI.ts"; import { StoreApiRequestFactory, StoreApiResponseProcessor} from "../apis/StoreApi.ts"; export interface StoreApiDeleteOrderRequest { /** * ID of the order that needs to be deleted * @type string * @memberof StoreApideleteOrder */ orderId: string } export interface StoreApiGetInventoryRequest { } export interface StoreApiGetOrderByIdRequest { /** * ID of pet that needs to be fetched * @type number * @memberof StoreApigetOrderById */ orderId: number } export interface StoreApiPlaceOrderRequest { /** * order placed for purchasing the pet * @type Order * @memberof StoreApiplaceOrder */ order: Order } export class ObjectStoreApi { private api: ObservableStoreApi public constructor(configuration: Configuration, requestFactory?: StoreApiRequestFactory, responseProcessor?: StoreApiResponseProcessor) { this.api = new ObservableStoreApi(configuration, requestFactory, responseProcessor); } /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID * @param param the request object */ public deleteOrder(param: StoreApiDeleteOrderRequest, options?: Configuration): Promise<void> { return this.api.deleteOrder(param.orderId, options).toPromise(); } /** * Returns a map of status codes to quantities * Returns pet inventories by status * @param param the request object */ public getInventory(param: StoreApiGetInventoryRequest, options?: Configuration): Promise<{ [key: string]: number; }> { return this.api.getInventory( options).toPromise(); } /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Find purchase order by ID * @param param the request object */ public getOrderById(param: StoreApiGetOrderByIdRequest, options?: Configuration): Promise<Order> { return this.api.getOrderById(param.orderId, options).toPromise(); } /** * Place an order for a pet * @param param the request object */ public placeOrder(param: StoreApiPlaceOrderRequest, options?: Configuration): Promise<Order> { return this.api.placeOrder(param.order, options).toPromise(); } } import { ObservableUserApi } from "./ObservableAPI.ts"; import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi.ts"; export interface UserApiCreateUserRequest { /** * Created user object * @type User * @memberof UserApicreateUser */ user: User } export interface UserApiCreateUsersWithArrayInputRequest { /** * List of user object * @type Array&lt;User&gt; * @memberof UserApicreateUsersWithArrayInput */ user: Array<User> } export interface UserApiCreateUsersWithListInputRequest { /** * List of user object * @type Array&lt;User&gt; * @memberof UserApicreateUsersWithListInput */ user: Array<User> } export interface UserApiDeleteUserRequest { /** * The name that needs to be deleted * @type string * @memberof UserApideleteUser */ username: string } export interface UserApiGetUserByNameRequest { /** * The name that needs to be fetched. Use user1 for testing. * @type string * @memberof UserApigetUserByName */ username: string } export interface UserApiLoginUserRequest { /** * The user name for login * @type string * @memberof UserApiloginUser */ username: string /** * The password for login in clear text * @type string * @memberof UserApiloginUser */ password: string } export interface UserApiLogoutUserRequest { } export interface UserApiUpdateUserRequest { /** * name that need to be deleted * @type string * @memberof UserApiupdateUser */ username: string /** * Updated user object * @type User * @memberof UserApiupdateUser */ user: User } export class ObjectUserApi { private api: ObservableUserApi public constructor(configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor) { this.api = new ObservableUserApi(configuration, requestFactory, responseProcessor); } /** * This can only be done by the logged in user. * Create user * @param param the request object */ public createUser(param: UserApiCreateUserRequest, options?: Configuration): Promise<void> { return this.api.createUser(param.user, options).toPromise(); } /** * Creates list of users with given input array * @param param the request object */ public createUsersWithArrayInput(param: UserApiCreateUsersWithArrayInputRequest, options?: Configuration): Promise<void> { return this.api.createUsersWithArrayInput(param.user, options).toPromise(); } /** * Creates list of users with given input array * @param param the request object */ public createUsersWithListInput(param: UserApiCreateUsersWithListInputRequest, options?: Configuration): Promise<void> { return this.api.createUsersWithListInput(param.user, options).toPromise(); } /** * This can only be done by the logged in user. * Delete user * @param param the request object */ public deleteUser(param: UserApiDeleteUserRequest, options?: Configuration): Promise<void> { return this.api.deleteUser(param.username, options).toPromise(); } /** * Get user by user name * @param param the request object */ public getUserByName(param: UserApiGetUserByNameRequest, options?: Configuration): Promise<User> { return this.api.getUserByName(param.username, options).toPromise(); } /** * Logs user into the system * @param param the request object */ public loginUser(param: UserApiLoginUserRequest, options?: Configuration): Promise<string> { return this.api.loginUser(param.username, param.password, options).toPromise(); } /** * Logs out current logged in user session * @param param the request object */ public logoutUser(param: UserApiLogoutUserRequest, options?: Configuration): Promise<void> { return this.api.logoutUser( options).toPromise(); } /** * This can only be done by the logged in user. * Updated user * @param param the request object */ public updateUser(param: UserApiUpdateUserRequest, options?: Configuration): Promise<void> { return this.api.updateUser(param.username, param.user, options).toPromise(); } }
the_stack
import * as areEqual from 'fbjs/lib/areEqual'; import * as invariant from 'fbjs/lib/invariant'; import * as warning from 'fbjs/lib/warning'; import { __internal, getSelector, IEnvironment, Disposable, Snapshot, Variables, getVariablesFromFragment, OperationDescriptor, getFragmentIdentifier, PluralReaderSelector, ReaderSelector, SingularReaderSelector, ReaderFragment, getDataIDsFromFragment, RequestDescriptor, } from 'relay-runtime'; import { Fetcher, fetchResolver } from './FetchResolver'; import { getConnectionState, getStateFromConnection } from './getConnectionState'; import { getPaginationMetadata } from './getPaginationMetadata'; import { getPaginationVariables } from './getPaginationVariables'; import { getRefetchMetadata } from './getRefetchMetadata'; import { getValueAtPath } from './getValueAtPath'; import { FragmentNames, Options, OptionsLoadMore, PAGINATION_NAME, REFETCHABLE_NAME, } from './RelayHooksTypes'; import { createOperation, forceCache } from './Utils'; const { getPromiseForActiveRequest } = __internal; type SingularOrPluralSnapshot = Snapshot | Array<Snapshot>; function lookupFragment(environment, selector): SingularOrPluralSnapshot { return selector.kind === 'PluralReaderSelector' ? selector.selectors.map((s) => environment.lookup(s)) : environment.lookup(selector); } function getFragmentResult(snapshot: SingularOrPluralSnapshot): any { const missData = isMissingData(snapshot); if (Array.isArray(snapshot)) { return { snapshot, data: snapshot.map((s) => s.data), isMissingData: missData }; } return { snapshot, data: snapshot.data, isMissingData: missData }; } type FragmentResult = { snapshot?: SingularOrPluralSnapshot | null; data: any; isMissingData?: boolean; owner?: any; }; function isMissingData(snapshot: SingularOrPluralSnapshot): boolean { if (Array.isArray(snapshot)) { return snapshot.some((s) => s.isMissingData); } return snapshot.isMissingData; } function getPromiseForPendingOperationAffectingOwner( environment: IEnvironment, request: RequestDescriptor, ): Promise<void> | null { return environment.getOperationTracker().getPromiseForPendingOperationsAffectingOwner(request); } function _getAndSavePromiseForFragmentRequestInFlight( fragmentOwner: RequestDescriptor, environment: IEnvironment, ): Promise<void> | null { const networkPromise = getPromiseForActiveRequest(environment, fragmentOwner) ?? getPromiseForPendingOperationAffectingOwner(environment, fragmentOwner); if (!networkPromise) { return null; } return networkPromise; } export class FragmentResolver { _environment: IEnvironment; _fragment: ReaderFragment; _fragmentRef: any; _fragmentRefRefetch: any; _idfragment: any; _idfragmentrefetch: any; resolverData: FragmentResult; _disposable: Disposable; _selector: ReaderSelector; refreshHooks: any; fetcherRefecth: Fetcher; fetcherNext: Fetcher; fetcherPrevious: Fetcher; unmounted = false; name: string; refetchable = false; pagination = false; result: any; _subscribeResolve; constructor(name: FragmentNames) { this.name = name; this.pagination = name === PAGINATION_NAME; this.refetchable = name === REFETCHABLE_NAME || this.pagination; const setLoading = (_loading): void => this.refreshHooks(); if (this.refetchable) { this.fetcherRefecth = fetchResolver({ setLoading, doRetain: true, }); } if (this.pagination) { this.fetcherNext = fetchResolver({ setLoading }); this.fetcherPrevious = fetchResolver({ setLoading }); } } setForceUpdate(forceUpdate = (): void => undefined): void { this.refreshHooks = (): void => { this.resolveResult(); forceUpdate(); }; } subscribeResolve(subscribeResolve: (data: any) => void): void { if (this._subscribeResolve && this._subscribeResolve != subscribeResolve) { subscribeResolve(this.getData()); } this._subscribeResolve = subscribeResolve; } setUnmounted(): void { this.unmounted = true; } isEqualsFragmentRef(prevFragment, fragmentRef): boolean { if (this._fragmentRef !== fragmentRef) { const prevIDs = getDataIDsFromFragment(this._fragment, prevFragment); const nextIDs = getDataIDsFromFragment(this._fragment, fragmentRef); if ( !areEqual(prevIDs, nextIDs) || !areEqual( this.getFragmentVariables(fragmentRef), this.getFragmentVariables(prevFragment), ) ) { return false; } } return true; } dispose(): void { this.unsubscribe(); this.fetcherNext && this.fetcherNext.dispose(); this.fetcherPrevious && this.fetcherPrevious.dispose(); this._idfragmentrefetch = null; this._fragmentRefRefetch = null; this.fetcherRefecth && this.fetcherRefecth.dispose(); } getFragmentVariables(fRef = this._fragmentRef): Variables { return getVariablesFromFragment(this._fragment, fRef); } resolve( environment: IEnvironment, idfragment: string, fragment: ReaderFragment, fragmentRef, ): void { if ( !this.resolverData || this._environment !== environment || (idfragment !== this._idfragment && (!this._idfragmentrefetch || (this._idfragmentrefetch && idfragment !== this._idfragmentrefetch))) ) { this._fragment = fragment; this._fragmentRef = fragmentRef; this._idfragment = idfragment; this._selector = null; this.dispose(); this._environment = environment; this.lookup(fragment, this._fragmentRef); this.resolveResult(); } } lookup(fragment, fragmentRef): void { if (fragmentRef == null) { this.resolverData = { data: null }; return; } const isPlural = fragment.metadata && fragment.metadata.plural && fragment.metadata.plural === true; if (isPlural) { if (fragmentRef.length === 0) { this.resolverData = { data: [] }; return; } } this._selector = getSelector(fragment, fragmentRef); const snapshot = lookupFragment(this._environment, this._selector); this.resolverData = getFragmentResult(snapshot); const owner = this._selector ? this._selector.kind === 'PluralReaderSelector' ? (this._selector as any).selectors[0].owner : (this._selector as any).owner : null; this.resolverData.owner = owner; //this.subscribe(); } checkAndSuspense(suspense): void { if (suspense && this.resolverData.isMissingData && this.resolverData.owner) { const fragmentOwner = this.resolverData.owner; const networkPromise = _getAndSavePromiseForFragmentRequestInFlight( fragmentOwner, this._environment, ); const parentQueryName = fragmentOwner.node.params.name ?? 'Unknown Parent Query'; if (networkPromise != null) { // When the Promise for the request resolves, we need to make sure to // update the cache with the latest data available in the store before // resolving the Promise const promise = networkPromise .then(() => { if (this._idfragmentrefetch) { this.resolveResult(); } else { this._idfragment = null; this.dispose(); } //; }) .catch((_error: Error) => { if (this._idfragmentrefetch) { this.resolveResult(); } else { this._idfragment = null; this.dispose(); } }); // $FlowExpectedError[prop-missing] Expando to annotate Promises. (promise as any).displayName = 'Relay(' + parentQueryName + ')'; this.unsubscribe(); this.refreshHooks = (): void => undefined; throw promise; } warning( false, 'Relay: Tried reading fragment `%s` declared in ' + '`%s`, but it has missing data and its parent query `%s` is not ' + 'being fetched.\n' + 'This might be fixed by by re-running the Relay Compiler. ' + ' Otherwise, make sure of the following:\n' + '* You are correctly fetching `%s` if you are using a ' + '"store-only" `fetchPolicy`.\n' + "* Other queries aren't accidentally fetching and overwriting " + 'the data for this fragment.\n' + '* Any related mutations or subscriptions are fetching all of ' + 'the data for this fragment.\n' + "* Any related store updaters aren't accidentally deleting " + 'data for this fragment.', this._fragment.name, this.name, parentQueryName, parentQueryName, ); } this.fetcherRefecth && this.fetcherRefecth.checkAndSuspense(suspense); } getData(): any | null { return this.result; } resolveResult(): any { const { data } = this.resolverData; if (this.refetchable || this.pagination) { const { isLoading, error } = this.fetcherRefecth.getData(); const refetch = this.refetch; if (!this.pagination) { // useRefetchable if ('production' !== process.env.NODE_ENV) { getRefetchMetadata(this._fragment, this.name); } this.result = { data, isLoading, error, refetch, }; } else { // usePagination const { connectionPathInFragmentData } = getPaginationMetadata( this._fragment, this.name, ); const connection = getValueAtPath(data, connectionPathInFragmentData); const { hasMore: hasNext } = getStateFromConnection( 'forward', this._fragment, connection, ); const { hasMore: hasPrevious } = getStateFromConnection( 'backward', this._fragment, connection, ); const { isLoading: isLoadingNext, error: errorNext } = this.fetcherNext.getData(); const { isLoading: isLoadingPrevious, error: errorPrevious, } = this.fetcherPrevious.getData(); this.result = { data, hasNext, isLoadingNext, hasPrevious, isLoadingPrevious, isLoading, errorNext, errorPrevious, error, refetch, loadNext: this.loadNext, loadPrevious: this.loadPrevious, }; } } else { // useFragment this.result = data; } this._subscribeResolve && this._subscribeResolve(this.result); } unsubscribe(): void { this._disposable && this._disposable.dispose(); } subscribe(): void { const environment = this._environment; const renderedSnapshot = this.resolverData.snapshot; this.unsubscribe(); const dataSubscriptions = []; if (renderedSnapshot) { if (Array.isArray(renderedSnapshot)) { renderedSnapshot.forEach((snapshot, idx) => { dataSubscriptions.push( environment.subscribe(snapshot, (latestSnapshot) => { this.resolverData.snapshot[idx] = latestSnapshot; this.resolverData.data[idx] = latestSnapshot.data; this.resolverData.isMissingData = false; this.refreshHooks(); }), ); }); } else { dataSubscriptions.push( environment.subscribe(renderedSnapshot, (latestSnapshot) => { this.resolverData = getFragmentResult(latestSnapshot); this.resolverData.isMissingData = false; this.refreshHooks(); }), ); } } this._disposable = { dispose: (): void => { dataSubscriptions.map((s) => s.dispose()); this._disposable = undefined; }, }; } refetch = (variables: Variables, options?: Options): Disposable => { if (this.unmounted === true) { warning( false, 'Relay: Unexpected call to `refetch` on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', this._fragment.name, this.name, ); return { dispose: (): void => {} }; } if (this._selector == null) { warning( false, 'Relay: Unexpected call to `refetch` while using a null fragment ref ' + 'for fragment `%s` in `%s`. When calling `refetch`, we expect ' + "initial fragment data to be non-null. Please make sure you're " + 'passing a valid fragment ref to `%s` before calling ' + '`refetch`, or make sure you pass all required variables to `refetch`.', this._fragment.name, this.name, this.name, ); } const { fragmentRefPathInResponse, identifierField, refetchableRequest, } = getRefetchMetadata(this._fragment, this.name); const fragmentData = this.getData().data; const identifierValue = identifierField != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierField] : null; let parentVariables; let fragmentVariables; if (this._selector == null) { parentVariables = {}; fragmentVariables = {}; } else if (this._selector.kind === 'PluralReaderSelector') { parentVariables = (this._selector as PluralReaderSelector).selectors[0]?.owner.variables ?? {}; fragmentVariables = (this._selector as PluralReaderSelector).selectors[0]?.variables ?? {}; } else { parentVariables = (this._selector as SingularReaderSelector).owner.variables; fragmentVariables = (this._selector as SingularReaderSelector).variables; } // NOTE: A user of `useRefetchableFragment()` may pass a subset of // all variables required by the fragment when calling `refetch()`. // We fill in any variables not passed by the call to `refetch()` with the // variables from the original parent fragment owner. /* $FlowFixMe[cannot-spread-indexer] (>=0.123.0) This comment suppresses * an error found when Flow v0.123.0 was deployed. To see the error * delete this comment and run Flow. */ const refetchVariables = { ...parentVariables, /* $FlowFixMe[exponential-spread] (>=0.111.0) This comment suppresses * an error found when Flow v0.111.0 was deployed. To see the error, * delete this comment and run Flow. */ ...fragmentVariables, ...variables, }; if (identifierField != null && !variables.hasOwnProperty('id')) { // @refetchable fragments are guaranteed to have an `id` selection // if the type is Node, implements Node, or is @fetchable. Double-check // that there actually is a value at runtime. if (typeof identifierValue !== 'string') { warning( false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierField, identifierValue, ); } refetchVariables.id = identifierValue; } const onNext = (operation: OperationDescriptor, snapshot: Snapshot): void => { const fragmentRef = getValueAtPath(snapshot.data, fragmentRefPathInResponse); const isEquals = this.isEqualsFragmentRef( this._fragmentRefRefetch || this._fragmentRef, fragmentRef, ); const missData = isMissingData(snapshot); //fromStore && isMissingData(snapshot); if (!isEquals || missData) { this._fragmentRefRefetch = fragmentRef; this._idfragmentrefetch = getFragmentIdentifier(this._fragment, fragmentRef); this.lookup(this._fragment, fragmentRef); this.subscribe(); /*if (!missData) { this.subscribe(); }*/ this.resolverData.isMissingData = missData; this.resolverData.owner = operation.request; this.refreshHooks(); } }; if (this.pagination) { this.fetcherNext.dispose(); this.fetcherPrevious.dispose(); } const operation = createOperation(refetchableRequest, refetchVariables, forceCache); return this.fetcherRefecth.fetch( this._environment, operation, options?.fetchPolicy, options?.onComplete, onNext, options?.UNSTABLE_renderPolicy, ); }; loadPrevious = (count: number, options?: OptionsLoadMore): Disposable => { return this.loadMore('backward', count, options); }; loadNext = (count: number, options?: OptionsLoadMore): Disposable => { return this.loadMore('forward', count, options); }; loadMore = ( direction: 'backward' | 'forward', count: number, options?: OptionsLoadMore, ): Disposable => { const onComplete = options?.onComplete ?? ((): void => undefined); const fragmentData = this.getData().data; const fetcher = direction === 'backward' ? this.fetcherPrevious : this.fetcherNext; if (this.unmounted === true) { // Bail out and warn if we're trying to paginate after the component // has unmounted warning( false, 'Relay: Unexpected fetch on unmounted component for fragment ' + '`%s` in `%s`. It looks like some instances of your component are ' + 'still trying to fetch data but they already unmounted. ' + 'Please make sure you clear all timers, intervals, ' + 'async calls, etc that may trigger a fetch.', this._fragment.name, this.name, ); return { dispose: (): void => {} }; } if (this._selector == null) { warning( false, 'Relay: Unexpected fetch while using a null fragment ref ' + 'for fragment `%s` in `%s`. When fetching more items, we expect ' + "initial fragment data to be non-null. Please make sure you're " + 'passing a valid fragment ref to `%s` before paginating.', this._fragment.name, this.name, this.name, ); onComplete(null); return { dispose: (): void => {} }; } const isRequestActive = (this._environment as any).isRequestActive( (this._selector as SingularReaderSelector).owner.identifier, ); if (isRequestActive || fetcher.getData().isLoading === true || fragmentData == null) { onComplete(null); return { dispose: (): void => {} }; } invariant( this._selector != null && this._selector.kind !== 'PluralReaderSelector', 'Relay: Expected to be able to find a non-plural fragment owner for ' + "fragment `%s` when using `%s`. If you're seeing this, " + 'this is likely a bug in Relay.', this._fragment.name, this.name, ); const { paginationRequest, paginationMetadata, identifierField, connectionPathInFragmentData, } = getPaginationMetadata(this._fragment, this.name); const identifierValue = identifierField != null && fragmentData != null && typeof fragmentData === 'object' ? fragmentData[identifierField] : null; const parentVariables = (this._selector as SingularReaderSelector).owner.variables; const fragmentVariables = (this._selector as SingularReaderSelector).variables; const extraVariables = options?.UNSTABLE_extraVariables; const baseVariables = { ...parentVariables, ...fragmentVariables, }; const { cursor } = getConnectionState( direction, this._fragment, fragmentData, connectionPathInFragmentData, ); const paginationVariables = getPaginationVariables( direction, count, cursor, baseVariables, { ...extraVariables }, paginationMetadata, ); // If the query needs an identifier value ('id' or similar) and one // was not explicitly provided, read it from the fragment data. if (identifierField != null) { // @refetchable fragments are guaranteed to have an `id` selection // if the type is Node, implements Node, or is @fetchable. Double-check // that there actually is a value at runtime. if (typeof identifierValue !== 'string') { warning( false, 'Relay: Expected result to have a string ' + '`%s` in order to refetch, got `%s`.', identifierField, identifierValue, ); } paginationVariables.id = identifierValue; } const onNext = (): void => {}; const operation = createOperation(paginationRequest, paginationVariables, forceCache); return fetcher.fetch( this._environment, operation, undefined, //options?.fetchPolicy, onComplete, onNext, ); }; }
the_stack
import { ActivatedRoute } from '@angular/router'; import { Store } from '@ngrx/store'; import { combineLatest, Observable } from 'rxjs'; import { filter, first, map, publishReplay, refCount, switchMap, tap } from 'rxjs/operators'; import { PermissionConfig } from '../../../../core/src/core/permissions/current-user-permissions.config'; import { CurrentUserPermissionsService } from '../../../../core/src/core/permissions/current-user-permissions.service'; import { getIdFromRoute, pathGet } from '../../../../core/src/core/utils.service'; import { extractActualListEntity, } from '../../../../core/src/shared/components/list/data-sources-controllers/local-filtering-sorting'; import { SetClientFilter } from '../../../../store/src/actions/pagination.actions'; import { RouterNav } from '../../../../store/src/actions/router.actions'; import { AppState } from '../../../../store/src/app-state'; import { PaginationMonitorFactory } from '../../../../store/src/monitors/pagination-monitor.factory'; import { getPaginationObservables } from '../../../../store/src/reducers/pagination-reducer/pagination-reducer.helper'; import { endpointEntitiesSelector } from '../../../../store/src/selectors/endpoint.selectors'; import { selectPaginationState } from '../../../../store/src/selectors/pagination.selectors'; import { APIResource } from '../../../../store/src/types/api.types'; import { EndpointModel } from '../../../../store/src/types/endpoint.types'; import { PaginatedAction, PaginationEntityState } from '../../../../store/src/types/pagination.types'; import { IServiceInstance, IUserProvidedServiceInstance } from '../../cf-api-svc.types'; import { CFFeatureFlagTypes, IApp, ISpace } from '../../cf-api.types'; import { CFAppState } from '../../cf-app-state'; import { cfEntityFactory } from '../../cf-entity-factory'; import { getCFEntityKey } from '../../cf-entity-helpers'; import { applicationEntityType } from '../../cf-entity-types'; import { CFEntityConfig } from '../../cf-types'; import { ListCfRoute } from '../../shared/components/list/list-types/cf-routes/cf-routes-data-source-base'; import { getCurrentUserCFEndpointRolesState } from '../../store/selectors/cf-current-user-role.selectors'; import { ICfRolesState } from '../../store/types/cf-current-user-roles.types'; import { CfUser, CfUserRoleParams, OrgUserRoleNames, SpaceUserRoleNames, UserRoleInOrg, UserRoleInSpace, } from '../../store/types/cf-user.types'; import { UserRoleLabels } from '../../store/types/users-roles.types'; import { CfCurrentUserPermissions, CfPermissionTypes } from '../../user-permissions/cf-user-permissions-checkers'; import { ActiveRouteCfCell, ActiveRouteCfOrgSpace } from './cf-page.types'; export interface IUserRole<T> { string: string; key: T; } export function getOrgRolesString(userRolesInOrg: UserRoleInOrg): string { let roles = null; if (userRolesInOrg[OrgUserRoleNames.MANAGER]) { roles = UserRoleLabels.org.short[OrgUserRoleNames.MANAGER]; } if (userRolesInOrg[OrgUserRoleNames.BILLING_MANAGERS]) { roles = assignRole(roles, UserRoleLabels.org.short[OrgUserRoleNames.BILLING_MANAGERS]); } if (userRolesInOrg[OrgUserRoleNames.AUDITOR]) { roles = assignRole(roles, UserRoleLabels.org.short[OrgUserRoleNames.AUDITOR]); } if (userRolesInOrg[OrgUserRoleNames.USER] && !userRolesInOrg[OrgUserRoleNames.MANAGER]) { roles = assignRole(roles, UserRoleLabels.org.short[OrgUserRoleNames.USER]); } return roles ? roles : 'None'; } export function getSpaceRolesString(userRolesInSpace: UserRoleInSpace): string { let roles = null; if (userRolesInSpace[SpaceUserRoleNames.MANAGER]) { roles = UserRoleLabels.space.short[SpaceUserRoleNames.MANAGER]; } if (userRolesInSpace[SpaceUserRoleNames.AUDITOR]) { roles = assignRole(roles, UserRoleLabels.space.short[SpaceUserRoleNames.AUDITOR]); } if (userRolesInSpace[SpaceUserRoleNames.DEVELOPER]) { roles = assignRole(roles, UserRoleLabels.space.short[SpaceUserRoleNames.DEVELOPER]); } return roles ? roles : 'None'; } export function getOrgRoles(userRolesInOrg: UserRoleInOrg): IUserRole<OrgUserRoleNames>[] { const roles = []; if (userRolesInOrg[OrgUserRoleNames.MANAGER]) { roles.push({ string: UserRoleLabels.org.short[OrgUserRoleNames.MANAGER], key: OrgUserRoleNames.MANAGER }); } if (userRolesInOrg[OrgUserRoleNames.BILLING_MANAGERS]) { roles.push({ string: UserRoleLabels.org.short[OrgUserRoleNames.BILLING_MANAGERS], key: OrgUserRoleNames.BILLING_MANAGERS }); } if (userRolesInOrg[OrgUserRoleNames.AUDITOR]) { roles.push({ string: UserRoleLabels.org.short[OrgUserRoleNames.AUDITOR], key: OrgUserRoleNames.AUDITOR }); } if (userRolesInOrg[OrgUserRoleNames.USER]) { roles.push({ string: UserRoleLabels.org.short[OrgUserRoleNames.USER], key: OrgUserRoleNames.USER }); } return roles; } export function getSpaceRoles(userRolesInSpace: UserRoleInSpace): IUserRole<SpaceUserRoleNames>[] { const roles = []; if (userRolesInSpace[SpaceUserRoleNames.MANAGER]) { roles.push({ string: UserRoleLabels.space.short[SpaceUserRoleNames.MANAGER], key: SpaceUserRoleNames.MANAGER }); } if (userRolesInSpace[SpaceUserRoleNames.AUDITOR]) { roles.push({ string: UserRoleLabels.space.short[SpaceUserRoleNames.AUDITOR], key: SpaceUserRoleNames.AUDITOR }); } if (userRolesInSpace[SpaceUserRoleNames.DEVELOPER]) { roles.push({ string: UserRoleLabels.space.short[SpaceUserRoleNames.DEVELOPER], key: SpaceUserRoleNames.DEVELOPER }); } return roles; } function assignRole(currentRoles: string, role: string) { const newRoles = currentRoles ? `${currentRoles}, ${role}` : role; return newRoles; } export function isOrgManager(user: CfUser, guid: string): boolean { return hasRole(user, guid, CfUserRoleParams.MANAGED_ORGS); } export function isOrgBillingManager(user: CfUser, guid: string): boolean { return hasRole(user, guid, CfUserRoleParams.BILLING_MANAGER_ORGS); } export function isOrgAuditor(user: CfUser, guid: string): boolean { return hasRole(user, guid, CfUserRoleParams.AUDITED_ORGS); } export function isOrgUser(user: CfUser, guid: string): boolean { return hasRole(user, guid, CfUserRoleParams.ORGANIZATIONS); } export function isSpaceManager(user: CfUser, spaceGuid: string): boolean { return hasRole(user, spaceGuid, CfUserRoleParams.MANAGED_SPACES); } export function isSpaceAuditor(user: CfUser, spaceGuid: string): boolean { return hasRole(user, spaceGuid, CfUserRoleParams.AUDITED_SPACES); } export function isSpaceDeveloper(user: CfUser, spaceGuid: string): boolean { return hasRole(user, spaceGuid, CfUserRoleParams.SPACES); } export function hasRoleWithinOrg(user: CfUser, orgGuid: string): boolean { return isOrgManager(user, orgGuid) || isOrgBillingManager(user, orgGuid) || isOrgAuditor(user, orgGuid) || isOrgUser(user, orgGuid); } export function hasRoleWithinSpace(user: CfUser, spaceGuid: string): boolean { return isSpaceManager(user, spaceGuid) || isSpaceAuditor(user, spaceGuid) || isSpaceDeveloper(user, spaceGuid); } export function hasRoleWithin(user: CfUser, orgGuid?: string, spaceGuid?: string): boolean { return hasRoleWithinOrg(user, orgGuid) || hasRoleWithinSpace(user, spaceGuid); } export function hasSpaceRoleWithinOrg(user: CfUser, orgGuid: string): boolean { const roles = [ CfUserRoleParams.MANAGED_SPACES, CfUserRoleParams.AUDITED_SPACES, CfUserRoleParams.SPACES ]; const orgSpaces = []; for (const role of roles) { const roleSpaces = user[role] as APIResource<ISpace>[]; orgSpaces.push(...roleSpaces.filter((space) => { return space.entity.organization_guid === orgGuid; })); } return orgSpaces.some((space) => hasRoleWithinSpace(user, space.metadata.guid)); } function hasRole(user: CfUser, guid: string, roleType: string) { if (user[roleType]) { const roles = user[roleType] as APIResource[]; return !!roles.find(o => o ? o.metadata.guid === guid : false); } return false; } export function getActiveRouteCfOrgSpace(activatedRoute: ActivatedRoute) { return ({ cfGuid: getIdFromRoute(activatedRoute, 'endpointId'), orgGuid: getIdFromRoute(activatedRoute, 'orgId'), spaceGuid: getIdFromRoute(activatedRoute, 'spaceId'), }); } export function getActiveRouteCfCell(activatedRoute: ActivatedRoute) { return ({ cfGuid: getIdFromRoute(activatedRoute, 'endpointId'), cellId: getIdFromRoute(activatedRoute, 'cellId'), }); } export const getActiveRouteCfOrgSpaceProvider = { provide: ActiveRouteCfOrgSpace, useFactory: getActiveRouteCfOrgSpace, deps: [ ActivatedRoute, ] }; export const getActiveRouteCfCellProvider = { provide: ActiveRouteCfCell, useFactory: getActiveRouteCfCell, deps: [ ActivatedRoute, ] }; export function goToAppWall(store: Store<CFAppState>, cfGuid: string, orgGuid?: string, spaceGuid?: string) { const appWallPagKey = 'applicationWall'; const entityKey = getCFEntityKey(applicationEntityType); store.dispatch(new SetClientFilter(new CFEntityConfig(applicationEntityType), appWallPagKey, { string: '', items: { cf: cfGuid, org: orgGuid, space: spaceGuid } } )); store.select(selectPaginationState(entityKey, appWallPagKey)).pipe( filter((state: PaginationEntityState) => { const items = pathGet('clientPagination.filter.items', state); return items ? items.cf === cfGuid && items.org === orgGuid && items.space === spaceGuid : false; }), first(), tap(() => { store.dispatch(new RouterNav({ path: ['applications'] })); }) ).subscribe(); } export function canUpdateOrgSpaceRoles( perms: CurrentUserPermissionsService, cfGuid: string, orgGuid?: string, spaceGuid?: string): Observable<boolean> { return combineLatest( perms.can(CfCurrentUserPermissions.ORGANIZATION_CHANGE_ROLES, cfGuid, orgGuid), perms.can(CfCurrentUserPermissions.SPACE_CHANGE_ROLES, cfGuid, orgGuid, spaceGuid) ).pipe( map((checks: boolean[]) => checks.some(check => check)) ); } export function canUpdateOrgRoles( perms: CurrentUserPermissionsService, cfGuid: string, orgGuid?: string): Observable<boolean> { return perms.can(CfCurrentUserPermissions.ORGANIZATION_CHANGE_ROLES, cfGuid, orgGuid); } export function waitForCFPermissions(store: Store<AppState>, cfGuid: string): Observable<ICfRolesState> { return store.select<ICfRolesState>(getCurrentUserCFEndpointRolesState(cfGuid)).pipe( filter(cf => cf && cf.state.initialised), first(), publishReplay(1), refCount(), ); } export function selectConnectedCfs(store: Store<AppState>): Observable<EndpointModel[]> { return store.select(endpointEntitiesSelector).pipe( map(endpoints => Object.values(endpoints)), map(endpoints => endpoints.filter(endpoint => endpoint.cnsi_type === 'cf' && endpoint.connectionStatus === 'connected')), ); } export function haveMultiConnectedCfs(store: Store<AppState>): Observable<boolean> { return selectConnectedCfs(store).pipe( map(connectedCfs => connectedCfs.length > 1) ); } export function filterEntitiesByGuid<T>(guid: string, array?: Array<APIResource<T>>): Array<APIResource<T>> { return array ? array.filter(entity => entity.metadata.guid === guid) : null; } export function createFetchTotalResultsPagKey(standardActionKey: string): string { return standardActionKey + '-totalResults'; } export function fetchTotalResults( action: PaginatedAction, store: Store<AppState>, paginationMonitorFactory: PaginationMonitorFactory ): Observable<number> { const newAction = { ...action, paginationKey: createFetchTotalResultsPagKey(action.paginationKey), flattenPagination: false, includeRelations: [] }; newAction.initialParams['results-per-page'] = 1; const pagObs = getPaginationObservables({ store, action: newAction, paginationMonitor: paginationMonitorFactory.create( newAction.paginationKey, cfEntityFactory(newAction.entityType), newAction.flattenPagination ) }, newAction.flattenPagination); return combineLatest( pagObs.entities$, // Ensure the request is made by sub'ing to the entities observable pagObs.pagination$ ).pipe( map(([, pagination]) => pagination), filter(pagination => !!pagination && !!pagination.pageRequests && !!pagination.pageRequests[1] && !pagination.pageRequests[1].busy), first(), map(pagination => pagination.totalResults) ); } type CfOrgSpaceFilterTypes = IApp | ListCfRoute | IServiceInstance; export const cfOrgSpaceFilter = (entities: APIResource[], paginationState: PaginationEntityState) => { // Filtering is done remotely when maxedResults are hit (see `setMultiFilter`) if (!!paginationState.maxedState.isMaxedMode && !paginationState.maxedState.ignoreMaxed) { return entities; } const fetchOrgGuid = (e: APIResource<CfOrgSpaceFilterTypes>): string => { return e.entity.space ? e.entity.space.entity.organization_guid : null; }; // Filter by cf/org/space const cfGuid = paginationState.clientPagination.filter.items.cf; const orgGuid = paginationState.clientPagination.filter.items.org; const spaceGuid = paginationState.clientPagination.filter.items.space; return !cfGuid && !orgGuid && !spaceGuid ? entities : entities.filter(e => { e = extractActualListEntity(e); const validCF = !(cfGuid && cfGuid !== e.entity.cfGuid); const validOrg = !(orgGuid && orgGuid !== fetchOrgGuid(e)); const validSpace = !(spaceGuid && spaceGuid !== e.entity.space_guid); return validCF && validOrg && validSpace; }); }; export function createCfOrgSpaceSteppersUrl( cfGuid: string, stepperPath: string = `/users/manage`, orgGuid?: string, spaceGuid?: string, ): string { let route = `/cloud-foundry/${cfGuid}`; if (orgGuid) { route += `/organizations/${orgGuid}`; if (spaceGuid) { route += `/spaces/${spaceGuid}`; } } route += stepperPath; return route; } export function createCfOrgSpaceUserRemovalUrl( cfGuid: string, orgGuid?: string, spaceGuid?: string, ): string { let route = `/cloud-foundry/${cfGuid}`; if (orgGuid) { route += `/organizations/${orgGuid}`; if (spaceGuid) { route += `/spaces/${spaceGuid}`; } } route += '/users/remove'; return route; } export function isServiceInstance(obj: any): IServiceInstance { return !!obj && !!obj.service_plan_url ? obj as IServiceInstance : null; } export function isUserProvidedServiceInstance(obj: any): IUserProvidedServiceInstance { return !!obj && (obj.route_service_url !== null && obj.route_service_url !== undefined) ? obj as IUserProvidedServiceInstance : null; } export function someFeatureFlags( ff: CFFeatureFlagTypes[], cfGuid: string, store: Store<AppState>, userPerms: CurrentUserPermissionsService, ): Observable<boolean> { return waitForCFPermissions(store, cfGuid).pipe( switchMap(() => combineLatest(ff.map(flag => { const permConfig = new PermissionConfig(CfPermissionTypes.FEATURE_FLAG, flag); return userPerms.can(permConfig, cfGuid); }))), map(results => results.some(result => !!result)) ); }
the_stack
'use strict'; // This must be the first statement otherwise modules might got loaded with // the wrong locale. import { TextEdit, Range, QuickPickItem, SnippetString, Command, EventEmitter, TreeItem, TreeDataProvider, commands, window, env, workspace, ExtensionContext, Uri, TreeItemCollapsibleState, WorkspaceEdit} from 'vscode'; import * as nls from 'vscode-nls'; nls.config({ locale: env.language }); import { WorkspaceLoadingNotification } from '../notifications/workspaceLoadingNotification'; import { TextEdit as VSCodeRpcTextEdit, RequestType, LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, NotificationType } from 'vscode-languageclient'; import * as path from 'path'; import * as fs from 'fs'; import { ModuleDescriptor, ModulesForWorkspaceParams, ModulesForWorkspaceRequest, ModulesForWorkspaceResult } from './modulesForWorkspaceRequest'; import { SpecDescriptor, RequestSpecsForModuleParams, SpecsForModulesRequest, SpecsFromModuleResult } from './specsForModuleParams'; import { sendAddSourceFileConfigurationToLanguageServer } from './addSourceFileConfigurationNotification'; import { configureAddSourceFile } from './addSourceFileRequest'; import { configureAddProject } from './addProjectRequest'; import * as assert from 'assert'; var languageClient : LanguageClient; var extensionContext: ExtensionContext; var createdProjectBrowser : boolean = false; // A map from the BuildXL module configuration path to the tree item // representing a BuildXL Module. Can eventually be used // to reveal the BuildXL module an opened file is located in. // This cannot be done yet due to bug: https://github.com/Microsoft/vscode/issues/30288 var modulePathToDominoModuleMap: Map<string, DominoModuleTreeItem>; /** * Represents a node in the project browser. */ interface DominoProjectBaseTreeItem { /** * Returns a a item to insert into the project browser tree. */ getTreeItem(): TreeItem; /** * Returns the children for this node. */ getChildren(): DominoProjectBaseTreeItem[]; } /** * Represents a BuildXL spec file in the project browser tree. */ export class DominoSpecFileTreeItem implements DominoProjectBaseTreeItem { constructor(specDescriptor: SpecDescriptor, showShortName: boolean) { this._specDescriptor = specDescriptor; this._showShortName = showShortName; } // The spec descriptor describing this spec file returned by the language server. private _specDescriptor : SpecDescriptor; // Indicated whether to use the short-name for the label (used in the solution\directory view) private _showShortName: boolean; /** * Returns a URI for the spec file that can be opened in the text editor. */ public uri() : Uri { // The files we get back from the language server need to have // the schema appened to them in order VSCode to understand them. return Uri.parse("file:///" + this._specDescriptor.fileName); } /** * Returns a "tree item" representing a BuildXL spec file for the project browser. */ public getTreeItem() : TreeItem { return { command: { arguments: [this, undefined], title: "Open", tooltip: "Open", command: 'dscript.openSpecData' }, contextValue: "dscript.spec", label: this._showShortName? path.basename(this._specDescriptor.fileName) : this._specDescriptor.fileName, collapsibleState: TreeItemCollapsibleState.None }; } /** * BuildXL spec files currently have no childern. */ public getChildren() : DominoProjectBaseTreeItem[] { return []; } } /** * Used to represent a solution like view based on directory * hierachy. */ class DirectoryTreeItem implements DominoProjectBaseTreeItem { constructor(directoryName: string) { this._directoryName = directoryName; this._retrieveSpecs = true; } // The single directory name (path-atom) that this item represents private _directoryName: string; // Indicates whether we have asked the language server // for the specs for a module. private _retrieveSpecs : boolean; // The list of project specs in this directory private _projectSpecs: SpecDescriptor[]; // The list of modules in this directory. private _modules: ModuleDescriptor[]; // A map from a single directory name (path-atom) // to the DirectoryTreeItem that represents it. private _childDirectories: Map<string, DirectoryTreeItem>; // Creates or retrieves a DirectoryTreeItem that represents // the passed in single directory name (path-atom) protected getOrAddSingleChild(directoryName: string) : DirectoryTreeItem { assert.equal(directoryName.includes(path.sep), false); // If this is the first time through, allocate the children if (this._childDirectories === undefined) { this._childDirectories = new Map<string, DirectoryTreeItem>(); } const directoryNameForMap = directoryName.toLowerCase(); // Create a new item if one does not exist for this directory. if (!this._childDirectories.has(directoryNameForMap)) { const newDirectoryTreeItem = new DirectoryTreeItem(directoryName); this._childDirectories.set(directoryNameForMap, newDirectoryTreeItem); // Let the tree view know that we've added a child. // This will cause the tree-view to re-acquire the childern. dominoDirectoryTreeEventEmitter.fire(this); return newDirectoryTreeItem; } return this._childDirectories.get(directoryNameForMap); } /** * Creates a hierarchy of DirectoryTreeItem's based on the specified path. * @returns A directory tree item representing the last portion of the passed in path. * @param directoryName The path to split apart and create a hierarchy of DirectoryTreeItems */ public getOrAddChild(directoryName: string) : DirectoryTreeItem { const paths = directoryName.split(path.sep); let nextDirectoryTreeItem : DirectoryTreeItem = this; paths.forEach((singlePath, index) => { nextDirectoryTreeItem = nextDirectoryTreeItem.getOrAddSingleChild(singlePath); }); return nextDirectoryTreeItem; } /** * Associates a module descriptor with this directory tree item. * @param mod The module to associate with this directory item. */ public addModule(mod: ModuleDescriptor) { if (this._modules === undefined) { this._modules = []; } this._modules.push(mod); // Let the tree view know that we've added a child. // This will cause the tree-view to re-acquire the childern. dominoDirectoryTreeEventEmitter.fire(this); } /** * Associates the spcified project spec file with this directory item. * @param projectSpec The project spec file to associate with this directory item. */ private addProjectSpec(projectSpec: SpecDescriptor) { if (this._projectSpecs === undefined) { this._projectSpecs = []; } this._projectSpecs.push(projectSpec); dominoDirectoryTreeEventEmitter.fire(this); } /** * Returns the tree item to the tree-view for this directory tree item. */ public getTreeItem() : TreeItem { return { // Set a context value used by the context menu contribution so // it knows this is a project directory. contextValue: "dscript.projectDirectory", // The label is simply the directory name label: this._directoryName, // The collapisble state has to check multiple things as it can have // multiple children. It needs to check for directories, project specs // and modules. collapsibleState: ((this._childDirectories && this._childDirectories.size !== 0) || (this._projectSpecs && this._projectSpecs.length !== 0) || (this._modules && this._modules.length !== 0) ) ? TreeItemCollapsibleState.Collapsed : TreeItemCollapsibleState.None }; } /** * Returns the children known to this directory. */ public getChildren() : DominoProjectBaseTreeItem[] { const directoryChildren: DominoProjectBaseTreeItem[] = []; // Add our child directories, sorted by name. if (this._childDirectories && this._childDirectories.size !== 0) { directoryChildren.push(...this._childDirectories.values()); directoryChildren.sort((a, b) => { return (<DirectoryTreeItem>a)._directoryName.localeCompare((<DirectoryTreeItem>b)._directoryName); }) } // Add our modules, sorted by module name. const moduleChildren: DominoProjectBaseTreeItem[] = []; if (this._modules && this._modules.length !== 0) { this._modules.forEach((mod) => { moduleChildren.push(new DominoModuleTreeItem(mod, dominoDirectoryTreeEventEmitter)); }); moduleChildren.sort((a, b) => { return (<DominoModuleTreeItem>a).descriptor().name.localeCompare((<DominoModuleTreeItem>b).descriptor().name); }) } // Add our project specs. const specChildren: DominoProjectBaseTreeItem[] = []; // If we have not asked the language server for the specs, then do so know. if (this._modules && this._modules.length !== 0 && this._retrieveSpecs) { this._retrieveSpecs = false; this._modules.forEach((mod) => { languageClient.sendRequest(SpecsForModulesRequest, <RequestSpecsForModuleParams>{moduleDescriptor: mod}).then((specs : SpecsFromModuleResult) => { specs.specs.forEach((spec, index) => { const directoryTreeItem = directoryTreeItems.getOrAddChild(path.dirname(spec.fileName)); directoryTreeItem.addProjectSpec(spec); }); }); }); } else { if (this._projectSpecs && this._projectSpecs.length !== 0) { this._projectSpecs.forEach((spec) => { specChildren.push(new DominoSpecFileTreeItem(spec, true)); }); specChildren.sort((a, b) => { return (<DominoSpecFileTreeItem>a).uri().fsPath.localeCompare((<DominoSpecFileTreeItem>b).uri().fsPath); }) } } // Finally return the child array which is a combination of all three types. return [...directoryChildren, ...moduleChildren, ...specChildren]; } } // The root directory tree item. const directoryTreeItems :DirectoryTreeItem = new DirectoryTreeItem(undefined); /** * Represents a BuildXL module in the project broweser tree. */ export class DominoModuleTreeItem implements DominoProjectBaseTreeItem { constructor(moduleDescriptor: ModuleDescriptor, eventEmiiter: EventEmitter<DominoProjectBaseTreeItem>) { this._moduleDescriptor = moduleDescriptor; this._collapseState = TreeItemCollapsibleState.Collapsed; this._eventEmiiter = eventEmiiter; } // The module description information returned from the language server. private _moduleDescriptor : ModuleDescriptor; private _children: DominoSpecFileTreeItem[]; private _collapseState: TreeItemCollapsibleState; private _eventEmiiter: EventEmitter<DominoProjectBaseTreeItem>; /** * Returns a "tree item" representing a module for the project browser. */ public getTreeItem() : TreeItem { return { contextValue: "dscript.module", label: this._moduleDescriptor.name, collapsibleState: this._collapseState }; } public expand() : void { // Note that this does not actually work due to // https://github.com/Microsoft/vscode/issues/40179 this._collapseState = TreeItemCollapsibleState.Expanded; this._eventEmiiter.fire(this); } public collapse() : void { this._collapseState = TreeItemCollapsibleState.Collapsed; this._eventEmiiter.fire(this); } /** * Returns the children of the BuildXL module, which, are currently spec files. */ public getChildren() :DominoProjectBaseTreeItem[] { if (this._children === undefined) { this._children = []; // Capture the this pointer in a block variable so it can // be used after the sendRequest completes. let moduleData = this; languageClient.sendRequest(SpecsForModulesRequest, <RequestSpecsForModuleParams>{ moduleDescriptor: this._moduleDescriptor}).then((specs : SpecsFromModuleResult) => { specs.specs.forEach((spec, index) => { moduleData._children.push(new DominoSpecFileTreeItem(spec, false)); }); // Now, fire the change event to the tree so that it calls the getChildren again moduleData._eventEmiiter.fire(moduleData); }); } return this._children; } /** * Returns the module descriptor for the item. */ public descriptor() : ModuleDescriptor { return this._moduleDescriptor; } } /** * The module list receieved from the langauge server */ var moduleTreeItems: DominoModuleTreeItem[]; /** * The event emitter for the project browser tree. */ const dominoModuleTreeEventEmitter = new EventEmitter<DominoProjectBaseTreeItem>(); /** * Creates the tree item provider for the module browser tree. */ function createModuleTreeDataProvider() : TreeDataProvider<DominoProjectBaseTreeItem> { return { getChildren: (element: DominoProjectBaseTreeItem): DominoProjectBaseTreeItem[] => { // Undefined means return the root items. if (element === undefined) { return moduleTreeItems; } return element.getChildren(); }, getTreeItem: (element: DominoProjectBaseTreeItem): TreeItem => { return element.getTreeItem(); }, onDidChangeTreeData: dominoModuleTreeEventEmitter.event }; } /** * The event emitter for the directory browser tree. */ const dominoDirectoryTreeEventEmitter = new EventEmitter<DominoProjectBaseTreeItem>(); /** * Creates the tree item provider for the directoy browser tree. */ function createDirectoryTreeDataProvider() : TreeDataProvider<DominoProjectBaseTreeItem> { return { getChildren: (element: DominoProjectBaseTreeItem): DominoProjectBaseTreeItem[] => { // Undefined means return the root items. if (element === undefined) { return directoryTreeItems.getChildren(); } return element.getChildren(); }, getTreeItem: (element: DominoProjectBaseTreeItem): TreeItem => { return element.getTreeItem(); }, onDidChangeTreeData: dominoDirectoryTreeEventEmitter.event }; } /** * Creates the BuildXL Project browser view * @param langClient The JSON-RPC language client, used to send requests to the language server * @param context The context the extennsion is running in, needed to register commands. */ export function createDominoProjectBrowser(langClient : LanguageClient, context: ExtensionContext) { // Read the configuration and see if we should do anything. const config = workspace.getConfiguration('dscript'); commands.executeCommand('setContext', 'dscript.moduleBrowserEnabled', config.turnOnModuleBrowser); commands.executeCommand('setContext', 'dscript.solutionExplorerEnabled', config.turnOnSolutionExplorer); if (!config.turnOnModuleBrowser && !config.turnOnSolutionExplorer) { return; } // If we've already created ourselves, then just bail out. // This can happen if we get multiple calls because the // user is changing their configuration settings. if (createdProjectBrowser) { return; } createdProjectBrowser = true; languageClient = langClient; extensionContext = context; // Register the command to be able to open spec documents when they are clicked on. context.subscriptions.push(commands.registerCommand('dscript.openSpecData', (spec: DominoSpecFileTreeItem) => { var textDocument = workspace.openTextDocument(spec.uri()).then((document) => { window.showTextDocument(document); }); } )); // Register the add source file command. configureAddSourceFile(languageClient, context); // Register the add project command. configureAddProject(languageClient, context); // Register for the workspace loading event so we know when the workspace // has successfully been loaded so we can start filling out the project browser WorkspaceLoadingNotification.WorkspaceLoadingEvent.event((state) => { if (state == WorkspaceLoadingNotification.WorkspaceLoadingState.Success) { moduleTreeItems = []; modulePathToDominoModuleMap = new Map<string, DominoModuleTreeItem>(); // Send the add source notification to the language server sendAddSourceFileConfigurationToLanguageServer(languageClient, context); languageClient.sendRequest(ModulesForWorkspaceRequest, <ModulesForWorkspaceParams>{includeSpecialConfigurationModules: false }).then((m : ModulesForWorkspaceResult) => { m.modules.sort((a,b) => { return a.name.localeCompare(b.name); }); m.modules.forEach((mod, index) => { const moduleConfigDirname = path.dirname(mod.configFilename); // Update the project module browser const dominoModuleTreeItem = new DominoModuleTreeItem(mod, dominoModuleTreeEventEmitter); modulePathToDominoModuleMap.set(moduleConfigDirname.toLowerCase(), dominoModuleTreeItem); moduleTreeItems.push(dominoModuleTreeItem); // Update the project directory browser. const moduleDirectoryItem = directoryTreeItems.getOrAddChild(moduleConfigDirname); moduleDirectoryItem.addModule(mod); }); dominoDirectoryTreeEventEmitter.fire(); dominoModuleTreeEventEmitter.fire(); }) } }); // Set up the BuildXL DScript project module browser. window.registerTreeDataProvider("dscriptBuildScope", createModuleTreeDataProvider()); // Set up the BuildXL DScript project directory browser. window.registerTreeDataProvider("buildxlProjectDirectoryBrowser", createDirectoryTreeDataProvider()); // Register for open document notifications so we can select the write module in the // tree view. workspace.onDidOpenTextDocument((document) => { // Note: Due to issue https://github.com/Microsoft/vscode/issues/30288 we cannot currently // do this. // I believe we would do something like this.. // As the user opens different documents we would find the closest // module configuration file for the open document. // If we find it, we would select the document in the BuildXL project browser. // We should be able to optimize this loop. if (modulePathToDominoModuleMap) { let docDirName = path.dirname(document.fileName).toLowerCase();; while (docDirName && docDirName.length > 0) { if (modulePathToDominoModuleMap.has(docDirName)) { modulePathToDominoModuleMap.get(docDirName).expand(); break; } // When we walk all the way to the root, stop. const newDirName = path.dirname(docDirName).toLowerCase(); if (newDirName === undefined || newDirName === docDirName) { break; } docDirName = newDirName; } } }); }
the_stack
import { DocumentNode } from "graphql"; import { makePrismaClientClass, BaseClientOptions, Model } from "prisma-client-lib"; import { typeDefs } from "./prisma-schema"; export type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]; export type Maybe<T> = T | undefined | null; export interface Exists { user: (where?: UserWhereInput) => Promise<boolean>; passwordMeta: (where?: PasswordMetaWhereInput) => Promise<boolean>; } export interface Node {} export type FragmentableArray<T> = Promise<Array<T>> & Fragmentable; export interface Fragmentable { $fragment<T>(fragment: string | DocumentNode): Promise<T>; } export interface Prisma { $exists: Exists; $graphql: <T = any>( query: string, variables?: { [key: string]: any } ) => Promise<T>; /** * Queries */ users: (args?: { where?: UserWhereInput; orderBy?: UserOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }) => FragmentableArray<User>; passwordMetas: (args?: { where?: PasswordMetaWhereInput; orderBy?: PasswordMetaOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }) => FragmentableArray<PasswordMeta>; user: (where: UserWhereUniqueInput) => UserNullablePromise; passwordMeta: ( where: PasswordMetaWhereUniqueInput ) => PasswordMetaNullablePromise; usersConnection: (args?: { where?: UserWhereInput; orderBy?: UserOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }) => UserConnectionPromise; passwordMetasConnection: (args?: { where?: PasswordMetaWhereInput; orderBy?: PasswordMetaOrderByInput; skip?: Int; after?: String; before?: String; first?: Int; last?: Int; }) => PasswordMetaConnectionPromise; node: (args: { id: ID_Output }) => Node; /** * Mutations */ createUser: (data: UserCreateInput) => UserPromise; createPasswordMeta: (data: PasswordMetaCreateInput) => PasswordMetaPromise; updateUser: (args: { data: UserUpdateInput; where: UserWhereUniqueInput; }) => UserPromise; updatePasswordMeta: (args: { data: PasswordMetaUpdateInput; where: PasswordMetaWhereUniqueInput; }) => PasswordMetaPromise; deleteUser: (where: UserWhereUniqueInput) => UserPromise; deletePasswordMeta: ( where: PasswordMetaWhereUniqueInput ) => PasswordMetaPromise; upsertUser: (args: { where: UserWhereUniqueInput; create: UserCreateInput; update: UserUpdateInput; }) => UserPromise; upsertPasswordMeta: (args: { where: PasswordMetaWhereUniqueInput; create: PasswordMetaCreateInput; update: PasswordMetaUpdateInput; }) => PasswordMetaPromise; updateManyUsers: (args: { data: UserUpdateManyMutationInput; where?: UserWhereInput; }) => BatchPayloadPromise; updateManyPasswordMetas: (args: { data: PasswordMetaUpdateManyMutationInput; where?: PasswordMetaWhereInput; }) => BatchPayloadPromise; deleteManyUsers: (where?: UserWhereInput) => BatchPayloadPromise; deleteManyPasswordMetas: ( where?: PasswordMetaWhereInput ) => BatchPayloadPromise; /** * Subscriptions */ $subscribe: Subscription; } export interface Subscription { user: ( where?: UserSubscriptionWhereInput ) => UserSubscriptionPayloadSubscription; passwordMeta: ( where?: PasswordMetaSubscriptionWhereInput ) => PasswordMetaSubscriptionPayloadSubscription; } export interface ClientConstructor<T> { new (options?: BaseClientOptions): T; } /** * Types */ export type UserOrderByInput = | "id_ASC" | "id_DESC" | "createdAt_ASC" | "createdAt_DESC" | "updatedAt_ASC" | "updatedAt_DESC" | "email_ASC" | "email_DESC" | "password_ASC" | "password_DESC" | "role_ASC" | "role_DESC" | "firstName_ASC" | "firstName_DESC" | "lastName_ASC" | "lastName_DESC" | "phone_ASC" | "phone_DESC"; export type UserRole = "USER" | "ADMIN"; export type MutationType = "CREATED" | "UPDATED" | "DELETED"; export type PasswordMetaOrderByInput = | "id_ASC" | "id_DESC" | "createdAt_ASC" | "createdAt_DESC" | "updatedAt_ASC" | "updatedAt_DESC" | "resetToken_ASC" | "resetToken_DESC"; export interface UserCreateInput { id?: Maybe<ID_Input>; email: String; password: String; role?: Maybe<UserRole>; firstName?: Maybe<String>; lastName?: Maybe<String>; phone?: Maybe<String>; passwordMeta?: Maybe<PasswordMetaCreateOneInput>; } export interface PasswordMetaUpdateInput { resetToken?: Maybe<String>; } export interface UserWhereInput { AND?: Maybe<UserWhereInput[] | UserWhereInput>; OR?: Maybe<UserWhereInput[] | UserWhereInput>; NOT?: Maybe<UserWhereInput[] | UserWhereInput>; id?: Maybe<ID_Input>; id_not?: Maybe<ID_Input>; id_in?: Maybe<ID_Input[] | ID_Input>; id_not_in?: Maybe<ID_Input[] | ID_Input>; id_lt?: Maybe<ID_Input>; id_lte?: Maybe<ID_Input>; id_gt?: Maybe<ID_Input>; id_gte?: Maybe<ID_Input>; id_contains?: Maybe<ID_Input>; id_not_contains?: Maybe<ID_Input>; id_starts_with?: Maybe<ID_Input>; id_not_starts_with?: Maybe<ID_Input>; id_ends_with?: Maybe<ID_Input>; id_not_ends_with?: Maybe<ID_Input>; createdAt?: Maybe<DateTimeInput>; createdAt_not?: Maybe<DateTimeInput>; createdAt_in?: Maybe<DateTimeInput[] | DateTimeInput>; createdAt_not_in?: Maybe<DateTimeInput[] | DateTimeInput>; createdAt_lt?: Maybe<DateTimeInput>; createdAt_lte?: Maybe<DateTimeInput>; createdAt_gt?: Maybe<DateTimeInput>; createdAt_gte?: Maybe<DateTimeInput>; updatedAt?: Maybe<DateTimeInput>; updatedAt_not?: Maybe<DateTimeInput>; updatedAt_in?: Maybe<DateTimeInput[] | DateTimeInput>; updatedAt_not_in?: Maybe<DateTimeInput[] | DateTimeInput>; updatedAt_lt?: Maybe<DateTimeInput>; updatedAt_lte?: Maybe<DateTimeInput>; updatedAt_gt?: Maybe<DateTimeInput>; updatedAt_gte?: Maybe<DateTimeInput>; email?: Maybe<String>; email_not?: Maybe<String>; email_in?: Maybe<String[] | String>; email_not_in?: Maybe<String[] | String>; email_lt?: Maybe<String>; email_lte?: Maybe<String>; email_gt?: Maybe<String>; email_gte?: Maybe<String>; email_contains?: Maybe<String>; email_not_contains?: Maybe<String>; email_starts_with?: Maybe<String>; email_not_starts_with?: Maybe<String>; email_ends_with?: Maybe<String>; email_not_ends_with?: Maybe<String>; password?: Maybe<String>; password_not?: Maybe<String>; password_in?: Maybe<String[] | String>; password_not_in?: Maybe<String[] | String>; password_lt?: Maybe<String>; password_lte?: Maybe<String>; password_gt?: Maybe<String>; password_gte?: Maybe<String>; password_contains?: Maybe<String>; password_not_contains?: Maybe<String>; password_starts_with?: Maybe<String>; password_not_starts_with?: Maybe<String>; password_ends_with?: Maybe<String>; password_not_ends_with?: Maybe<String>; role?: Maybe<UserRole>; role_not?: Maybe<UserRole>; role_in?: Maybe<UserRole[] | UserRole>; role_not_in?: Maybe<UserRole[] | UserRole>; firstName?: Maybe<String>; firstName_not?: Maybe<String>; firstName_in?: Maybe<String[] | String>; firstName_not_in?: Maybe<String[] | String>; firstName_lt?: Maybe<String>; firstName_lte?: Maybe<String>; firstName_gt?: Maybe<String>; firstName_gte?: Maybe<String>; firstName_contains?: Maybe<String>; firstName_not_contains?: Maybe<String>; firstName_starts_with?: Maybe<String>; firstName_not_starts_with?: Maybe<String>; firstName_ends_with?: Maybe<String>; firstName_not_ends_with?: Maybe<String>; lastName?: Maybe<String>; lastName_not?: Maybe<String>; lastName_in?: Maybe<String[] | String>; lastName_not_in?: Maybe<String[] | String>; lastName_lt?: Maybe<String>; lastName_lte?: Maybe<String>; lastName_gt?: Maybe<String>; lastName_gte?: Maybe<String>; lastName_contains?: Maybe<String>; lastName_not_contains?: Maybe<String>; lastName_starts_with?: Maybe<String>; lastName_not_starts_with?: Maybe<String>; lastName_ends_with?: Maybe<String>; lastName_not_ends_with?: Maybe<String>; phone?: Maybe<String>; phone_not?: Maybe<String>; phone_in?: Maybe<String[] | String>; phone_not_in?: Maybe<String[] | String>; phone_lt?: Maybe<String>; phone_lte?: Maybe<String>; phone_gt?: Maybe<String>; phone_gte?: Maybe<String>; phone_contains?: Maybe<String>; phone_not_contains?: Maybe<String>; phone_starts_with?: Maybe<String>; phone_not_starts_with?: Maybe<String>; phone_ends_with?: Maybe<String>; phone_not_ends_with?: Maybe<String>; passwordMeta?: Maybe<PasswordMetaWhereInput>; } export interface PasswordMetaUpsertNestedInput { update: PasswordMetaUpdateDataInput; create: PasswordMetaCreateInput; } export interface PasswordMetaWhereInput { AND?: Maybe<PasswordMetaWhereInput[] | PasswordMetaWhereInput>; OR?: Maybe<PasswordMetaWhereInput[] | PasswordMetaWhereInput>; NOT?: Maybe<PasswordMetaWhereInput[] | PasswordMetaWhereInput>; id?: Maybe<ID_Input>; id_not?: Maybe<ID_Input>; id_in?: Maybe<ID_Input[] | ID_Input>; id_not_in?: Maybe<ID_Input[] | ID_Input>; id_lt?: Maybe<ID_Input>; id_lte?: Maybe<ID_Input>; id_gt?: Maybe<ID_Input>; id_gte?: Maybe<ID_Input>; id_contains?: Maybe<ID_Input>; id_not_contains?: Maybe<ID_Input>; id_starts_with?: Maybe<ID_Input>; id_not_starts_with?: Maybe<ID_Input>; id_ends_with?: Maybe<ID_Input>; id_not_ends_with?: Maybe<ID_Input>; createdAt?: Maybe<DateTimeInput>; createdAt_not?: Maybe<DateTimeInput>; createdAt_in?: Maybe<DateTimeInput[] | DateTimeInput>; createdAt_not_in?: Maybe<DateTimeInput[] | DateTimeInput>; createdAt_lt?: Maybe<DateTimeInput>; createdAt_lte?: Maybe<DateTimeInput>; createdAt_gt?: Maybe<DateTimeInput>; createdAt_gte?: Maybe<DateTimeInput>; updatedAt?: Maybe<DateTimeInput>; updatedAt_not?: Maybe<DateTimeInput>; updatedAt_in?: Maybe<DateTimeInput[] | DateTimeInput>; updatedAt_not_in?: Maybe<DateTimeInput[] | DateTimeInput>; updatedAt_lt?: Maybe<DateTimeInput>; updatedAt_lte?: Maybe<DateTimeInput>; updatedAt_gt?: Maybe<DateTimeInput>; updatedAt_gte?: Maybe<DateTimeInput>; resetToken?: Maybe<String>; resetToken_not?: Maybe<String>; resetToken_in?: Maybe<String[] | String>; resetToken_not_in?: Maybe<String[] | String>; resetToken_lt?: Maybe<String>; resetToken_lte?: Maybe<String>; resetToken_gt?: Maybe<String>; resetToken_gte?: Maybe<String>; resetToken_contains?: Maybe<String>; resetToken_not_contains?: Maybe<String>; resetToken_starts_with?: Maybe<String>; resetToken_not_starts_with?: Maybe<String>; resetToken_ends_with?: Maybe<String>; resetToken_not_ends_with?: Maybe<String>; } export interface PasswordMetaUpdateDataInput { resetToken?: Maybe<String>; } export interface PasswordMetaUpdateManyMutationInput { resetToken?: Maybe<String>; } export interface UserUpdateManyMutationInput { email?: Maybe<String>; password?: Maybe<String>; role?: Maybe<UserRole>; firstName?: Maybe<String>; lastName?: Maybe<String>; phone?: Maybe<String>; } export interface PasswordMetaCreateOneInput { create?: Maybe<PasswordMetaCreateInput>; connect?: Maybe<PasswordMetaWhereUniqueInput>; } export interface PasswordMetaCreateInput { id?: Maybe<ID_Input>; resetToken: String; } export interface UserUpdateInput { email?: Maybe<String>; password?: Maybe<String>; role?: Maybe<UserRole>; firstName?: Maybe<String>; lastName?: Maybe<String>; phone?: Maybe<String>; passwordMeta?: Maybe<PasswordMetaUpdateOneInput>; } export interface PasswordMetaUpdateOneInput { create?: Maybe<PasswordMetaCreateInput>; connect?: Maybe<PasswordMetaWhereUniqueInput>; disconnect?: Maybe<Boolean>; delete?: Maybe<Boolean>; update?: Maybe<PasswordMetaUpdateDataInput>; upsert?: Maybe<PasswordMetaUpsertNestedInput>; } export interface PasswordMetaSubscriptionWhereInput { AND?: Maybe< PasswordMetaSubscriptionWhereInput[] | PasswordMetaSubscriptionWhereInput >; OR?: Maybe< PasswordMetaSubscriptionWhereInput[] | PasswordMetaSubscriptionWhereInput >; NOT?: Maybe< PasswordMetaSubscriptionWhereInput[] | PasswordMetaSubscriptionWhereInput >; mutation_in?: Maybe<MutationType[] | MutationType>; updatedFields_contains?: Maybe<String>; updatedFields_contains_every?: Maybe<String[] | String>; updatedFields_contains_some?: Maybe<String[] | String>; node?: Maybe<PasswordMetaWhereInput>; } export interface UserSubscriptionWhereInput { AND?: Maybe<UserSubscriptionWhereInput[] | UserSubscriptionWhereInput>; OR?: Maybe<UserSubscriptionWhereInput[] | UserSubscriptionWhereInput>; NOT?: Maybe<UserSubscriptionWhereInput[] | UserSubscriptionWhereInput>; mutation_in?: Maybe<MutationType[] | MutationType>; updatedFields_contains?: Maybe<String>; updatedFields_contains_every?: Maybe<String[] | String>; updatedFields_contains_some?: Maybe<String[] | String>; node?: Maybe<UserWhereInput>; } export type PasswordMetaWhereUniqueInput = AtLeastOne<{ id: Maybe<ID_Input>; }>; export type UserWhereUniqueInput = AtLeastOne<{ id: Maybe<ID_Input>; email?: Maybe<String>; }>; /* * An object with an ID */ export interface NodeNode { id: ID_Output; } /* * An edge in a connection. */ export interface PasswordMetaEdge { node: PasswordMeta; cursor: String; } /* * An edge in a connection. */ export interface PasswordMetaEdgePromise extends Promise<PasswordMetaEdge>, Fragmentable { node: <T = PasswordMetaPromise>() => T; cursor: () => Promise<String>; } /* * An edge in a connection. */ export interface PasswordMetaEdgeSubscription extends Promise<AsyncIterator<PasswordMetaEdge>>, Fragmentable { node: <T = PasswordMetaSubscription>() => T; cursor: () => Promise<AsyncIterator<String>>; } export interface BatchPayload { count: Long; } export interface BatchPayloadPromise extends Promise<BatchPayload>, Fragmentable { count: () => Promise<Long>; } export interface BatchPayloadSubscription extends Promise<AsyncIterator<BatchPayload>>, Fragmentable { count: () => Promise<AsyncIterator<Long>>; } export interface PasswordMetaPreviousValues { id: ID_Output; createdAt: DateTimeOutput; updatedAt: DateTimeOutput; resetToken: String; } export interface PasswordMetaPreviousValuesPromise extends Promise<PasswordMetaPreviousValues>, Fragmentable { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; resetToken: () => Promise<String>; } export interface PasswordMetaPreviousValuesSubscription extends Promise<AsyncIterator<PasswordMetaPreviousValues>>, Fragmentable { id: () => Promise<AsyncIterator<ID_Output>>; createdAt: () => Promise<AsyncIterator<DateTimeOutput>>; updatedAt: () => Promise<AsyncIterator<DateTimeOutput>>; resetToken: () => Promise<AsyncIterator<String>>; } export interface AggregatePasswordMeta { count: Int; } export interface AggregatePasswordMetaPromise extends Promise<AggregatePasswordMeta>, Fragmentable { count: () => Promise<Int>; } export interface AggregatePasswordMetaSubscription extends Promise<AsyncIterator<AggregatePasswordMeta>>, Fragmentable { count: () => Promise<AsyncIterator<Int>>; } /* * A connection to a list of items. */ export interface PasswordMetaConnection { pageInfo: PageInfo; edges: PasswordMetaEdge[]; } /* * A connection to a list of items. */ export interface PasswordMetaConnectionPromise extends Promise<PasswordMetaConnection>, Fragmentable { pageInfo: <T = PageInfoPromise>() => T; edges: <T = FragmentableArray<PasswordMetaEdge>>() => T; aggregate: <T = AggregatePasswordMetaPromise>() => T; } /* * A connection to a list of items. */ export interface PasswordMetaConnectionSubscription extends Promise<AsyncIterator<PasswordMetaConnection>>, Fragmentable { pageInfo: <T = PageInfoSubscription>() => T; edges: <T = Promise<AsyncIterator<PasswordMetaEdgeSubscription>>>() => T; aggregate: <T = AggregatePasswordMetaSubscription>() => T; } export interface User extends Node { id: ID_Output; createdAt: DateTimeOutput; updatedAt: DateTimeOutput; email: String; password: String; role: UserRole; firstName?: String; lastName?: String; phone?: String; } export interface UserPromise extends Promise<User>, Fragmentable, Node { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; email: () => Promise<String>; password: () => Promise<String>; role: () => Promise<UserRole>; firstName: () => Promise<String>; lastName: () => Promise<String>; phone: () => Promise<String>; passwordMeta: <T = PasswordMetaPromise>() => T; } export interface UserSubscription extends Promise<AsyncIterator<User>>, Fragmentable, Node { id: () => Promise<AsyncIterator<ID_Output>>; createdAt: () => Promise<AsyncIterator<DateTimeOutput>>; updatedAt: () => Promise<AsyncIterator<DateTimeOutput>>; email: () => Promise<AsyncIterator<String>>; password: () => Promise<AsyncIterator<String>>; role: () => Promise<AsyncIterator<UserRole>>; firstName: () => Promise<AsyncIterator<String>>; lastName: () => Promise<AsyncIterator<String>>; phone: () => Promise<AsyncIterator<String>>; passwordMeta: <T = PasswordMetaSubscription>() => T; } export interface UserNullablePromise extends Promise<User | null>, Fragmentable, Node { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; email: () => Promise<String>; password: () => Promise<String>; role: () => Promise<UserRole>; firstName: () => Promise<String>; lastName: () => Promise<String>; phone: () => Promise<String>; passwordMeta: <T = PasswordMetaPromise>() => T; } /* * An edge in a connection. */ export interface UserEdge { node: User; cursor: String; } /* * An edge in a connection. */ export interface UserEdgePromise extends Promise<UserEdge>, Fragmentable { node: <T = UserPromise>() => T; cursor: () => Promise<String>; } /* * An edge in a connection. */ export interface UserEdgeSubscription extends Promise<AsyncIterator<UserEdge>>, Fragmentable { node: <T = UserSubscription>() => T; cursor: () => Promise<AsyncIterator<String>>; } export interface UserSubscriptionPayload { mutation: MutationType; node: User; updatedFields: String[]; previousValues: UserPreviousValues; } export interface UserSubscriptionPayloadPromise extends Promise<UserSubscriptionPayload>, Fragmentable { mutation: () => Promise<MutationType>; node: <T = UserPromise>() => T; updatedFields: () => Promise<String[]>; previousValues: <T = UserPreviousValuesPromise>() => T; } export interface UserSubscriptionPayloadSubscription extends Promise<AsyncIterator<UserSubscriptionPayload>>, Fragmentable { mutation: () => Promise<AsyncIterator<MutationType>>; node: <T = UserSubscription>() => T; updatedFields: () => Promise<AsyncIterator<String[]>>; previousValues: <T = UserPreviousValuesSubscription>() => T; } /* * A connection to a list of items. */ export interface UserConnection { pageInfo: PageInfo; edges: UserEdge[]; } /* * A connection to a list of items. */ export interface UserConnectionPromise extends Promise<UserConnection>, Fragmentable { pageInfo: <T = PageInfoPromise>() => T; edges: <T = FragmentableArray<UserEdge>>() => T; aggregate: <T = AggregateUserPromise>() => T; } /* * A connection to a list of items. */ export interface UserConnectionSubscription extends Promise<AsyncIterator<UserConnection>>, Fragmentable { pageInfo: <T = PageInfoSubscription>() => T; edges: <T = Promise<AsyncIterator<UserEdgeSubscription>>>() => T; aggregate: <T = AggregateUserSubscription>() => T; } export interface UserPreviousValues { id: ID_Output; createdAt: DateTimeOutput; updatedAt: DateTimeOutput; email: String; password: String; role: UserRole; firstName?: String; lastName?: String; phone?: String; } export interface UserPreviousValuesPromise extends Promise<UserPreviousValues>, Fragmentable { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; email: () => Promise<String>; password: () => Promise<String>; role: () => Promise<UserRole>; firstName: () => Promise<String>; lastName: () => Promise<String>; phone: () => Promise<String>; } export interface UserPreviousValuesSubscription extends Promise<AsyncIterator<UserPreviousValues>>, Fragmentable { id: () => Promise<AsyncIterator<ID_Output>>; createdAt: () => Promise<AsyncIterator<DateTimeOutput>>; updatedAt: () => Promise<AsyncIterator<DateTimeOutput>>; email: () => Promise<AsyncIterator<String>>; password: () => Promise<AsyncIterator<String>>; role: () => Promise<AsyncIterator<UserRole>>; firstName: () => Promise<AsyncIterator<String>>; lastName: () => Promise<AsyncIterator<String>>; phone: () => Promise<AsyncIterator<String>>; } export interface AggregateUser { count: Int; } export interface AggregateUserPromise extends Promise<AggregateUser>, Fragmentable { count: () => Promise<Int>; } export interface AggregateUserSubscription extends Promise<AsyncIterator<AggregateUser>>, Fragmentable { count: () => Promise<AsyncIterator<Int>>; } export interface PasswordMetaSubscriptionPayload { mutation: MutationType; node: PasswordMeta; updatedFields: String[]; previousValues: PasswordMetaPreviousValues; } export interface PasswordMetaSubscriptionPayloadPromise extends Promise<PasswordMetaSubscriptionPayload>, Fragmentable { mutation: () => Promise<MutationType>; node: <T = PasswordMetaPromise>() => T; updatedFields: () => Promise<String[]>; previousValues: <T = PasswordMetaPreviousValuesPromise>() => T; } export interface PasswordMetaSubscriptionPayloadSubscription extends Promise<AsyncIterator<PasswordMetaSubscriptionPayload>>, Fragmentable { mutation: () => Promise<AsyncIterator<MutationType>>; node: <T = PasswordMetaSubscription>() => T; updatedFields: () => Promise<AsyncIterator<String[]>>; previousValues: <T = PasswordMetaPreviousValuesSubscription>() => T; } export interface PasswordMeta extends Node { id: ID_Output; createdAt: DateTimeOutput; updatedAt: DateTimeOutput; resetToken: String; } export interface PasswordMetaPromise extends Promise<PasswordMeta>, Fragmentable, Node { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; resetToken: () => Promise<String>; } export interface PasswordMetaSubscription extends Promise<AsyncIterator<PasswordMeta>>, Fragmentable, Node { id: () => Promise<AsyncIterator<ID_Output>>; createdAt: () => Promise<AsyncIterator<DateTimeOutput>>; updatedAt: () => Promise<AsyncIterator<DateTimeOutput>>; resetToken: () => Promise<AsyncIterator<String>>; } export interface PasswordMetaNullablePromise extends Promise<PasswordMeta | null>, Fragmentable, Node { id: () => Promise<ID_Output>; createdAt: () => Promise<DateTimeOutput>; updatedAt: () => Promise<DateTimeOutput>; resetToken: () => Promise<String>; } /* * Information about pagination in a connection. */ export interface PageInfo { hasNextPage: Boolean; hasPreviousPage: Boolean; startCursor?: String; endCursor?: String; } /* * Information about pagination in a connection. */ export interface PageInfoPromise extends Promise<PageInfo>, Fragmentable { hasNextPage: () => Promise<Boolean>; hasPreviousPage: () => Promise<Boolean>; startCursor: () => Promise<String>; endCursor: () => Promise<String>; } /* * Information about pagination in a connection. */ export interface PageInfoSubscription extends Promise<AsyncIterator<PageInfo>>, Fragmentable { hasNextPage: () => Promise<AsyncIterator<Boolean>>; hasPreviousPage: () => Promise<AsyncIterator<Boolean>>; startCursor: () => Promise<AsyncIterator<String>>; endCursor: () => Promise<AsyncIterator<String>>; } /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number; /* The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ export type Long = string; /* The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID. */ export type ID_Input = string | number; export type ID_Output = string; /* DateTime scalar input type, allowing Date */ export type DateTimeInput = Date | string; /* DateTime scalar output type, which is always a string */ export type DateTimeOutput = string; /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean; /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string; /** * Model Metadata */ export const models: Model[] = [ { name: "UserRole", embedded: false }, { name: "User", embedded: false }, { name: "PasswordMeta", embedded: false } ]; /** * Type Defs */ export const Prisma = makePrismaClientClass<ClientConstructor<Prisma>>({ typeDefs, models, endpoint: `${process.env["PRISMA_ENDPOINT"]}`, secret: `${process.env["PRISMA_SECRET"]}` }); export const prisma = new Prisma();
the_stack
import { ComponentFactoryResolver, ComponentRef, Directive, ElementRef, EventEmitter, Host, Input, OnChanges, OnDestroy, OnInit, Optional, Output, Self, SimpleChanges, SkipSelf } from '@angular/core'; import { AbstractControl, AbstractControlDirective, AsyncValidatorFn, ControlContainer, NgControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { I18nInterface, I18nService } from 'ng-devui/i18n'; import { OverlayContainerRef } from 'ng-devui/overlay-container'; import { PopoverComponent } from 'ng-devui/popover'; import { fromEvent, merge, Observable, Subject, timer } from 'rxjs'; import { map, switchMap, takeUntil } from 'rxjs/operators'; import { FormItemComponent } from '../form-item.component'; import { DAsyncValidateRule, dDefaultValidators, DFormControlStatus, DPopConfig, DValidateErrorStatus, DValidateRule, DValidateRules, DValidationErrorStrategy, ruleReservedWords } from './validate.type'; @Directive() export abstract class DAbstractControlRuleDirective implements OnChanges { /* mode is _cd.control */ public readonly _cd: AbstractControlDirective; // model is _cd.control /* parent dValidateRuleDirective */ private _parent: DAbstractControlRuleDirective; /* 预置rules: originRules */ private _originRules: DValidateRules; /* rules */ private _rules: DValidateRules; /* 统一设置错误抛出策略 */ private _errorStrategy: DValidationErrorStrategy = 'dirty'; // 统一设置错误抛出策略 /* rules map */ private _messageOpts: { [key: string]: DValidateRule | DAsyncValidateRule }; /* 是否已经注册监听 */ private _registered = false; public readonly errors: { [key: string]: any } | null; private _errorMessage: string = null; /* status warning */ private _warning: boolean; /* 内置国际化text */ i18nFormText: I18nInterface['form']; /* language key */ _locale: string; set locale(key: string) { this._locale = key; this._parseErrors(this._cd.control.errors); this.updateStatusAndMessageToView(this._cd.control.status); } get locale(): string { return this._locale; } public get errorMessage() { return this._cd && this._cd.control.invalid ? this._errorMessage || (this._rules && (this._rules as { message: string }).message) : null; } public set errorMessage(msg: string) { if (this._cd && this._cd.control.invalid) { this._errorMessage = msg; } else { this._errorMessage = null; } } @Output() dRulesStatusChange = new EventEmitter<DValidateErrorStatus>(); constructor(cd: AbstractControlDirective, parent: DAbstractControlRuleDirective) { this._cd = cd; this._parent = parent; } get isReady() { return this._cd.control ? !(this._cd.control.invalid || this._cd.control.pending) : true; } get pending() { return this._cd.control ? this._cd.control.pending : true; } /* 包含继承自父级的rule */ get fullRules(): DValidateRules { const keysCanInherit = ['messageShowType', 'errorStrategy', 'messageToView', 'popPosition', 'asyncDebounceTime']; const resRules = { ...this._rules }; keysCanInherit.forEach((key) => { if (this._parent && this._parent.fullRules) { resRules[key] = resRules[key] !== undefined ? resRules[key] : this._parent.fullRules[key]; } }); return resRules; } get asyncValidatorDebounceTime(): number { const time = (this.fullRules as { asyncDebounceTime: number }).asyncDebounceTime; return time === undefined ? 300 : time; } ngOnChanges(changes: SimpleChanges): void { if ('rules' in changes && !this._rules) { // TODO:提供外部调用可手动更新rule方法 this._rules = { ...this._originRules, ...this._translateRulesToObject(changes['rules'].currentValue) }; this.setupOrUpdateRules(); } if (!this._registered) { this._registerOnStatusChange(); } } public updateRules(rules: DValidateRules): void { this._rules = { ...this._originRules, ...this._translateRulesToObject(rules) }; this.setupOrUpdateRules(); } public setOriginRules(rules: DValidateRules): void { this._originRules = this._translateRulesToObject(rules); } public setupOrUpdateRules(): void { // TODO:校验rules规则是否合法 this._transformRulesAndUpdateToModel(); this._setUpdateStrategy(); } private _transformRulesAndUpdateToModel(): void { this._messageOpts = {}; if (!Array.isArray(this._rules)) { if (this._rules.validators) { const validators: ValidatorFn[] = this._transformValidatorsToFnArray(this._rules.validators) as ValidatorFn[]; this._updateValidators(validators); } if (this._rules.asyncValidators) { const asyncValidators: AsyncValidatorFn[] = this._transformValidatorsToFnArray( this._rules.asyncValidators, true ) as AsyncValidatorFn[]; this._updateAsyncValidators(asyncValidators); } } else { const validators: ValidatorFn[] = this._transformValidatorsToFnArray(this._rules) as ValidatorFn[]; this._updateValidators(validators); } this._updateValueAndValidity(); } private _transformValidatorsToFnArray( validators: DValidateRule[] | DAsyncValidateRule[], async = false ): ValidatorFn[] | AsyncValidatorFn[] { const resultFns = []; validators.forEach((validatorRule: DValidateRule) => { // TODO: 提供可全局统一注册方法 const validatorId: string = this._autoGetIdFromRule(validatorRule); let validator = null; if (!validatorId) { // TODO:抛出错误 } if (validatorId in dDefaultValidators) { validator = this._generateValidatorFnFromDefault(validatorId, validatorRule[validatorId]); } else { if (typeof validatorRule[validatorId] === 'string') { validator = validatorRule.validator; } else { validator = validatorRule[validatorId]; } if (!validatorRule.isNgValidator) { if (!async) { validator = this._transformRuleToNgValidator(validatorId, validator, validatorRule.message); } else { validator = this._transformRuleToNgAsyncValidator(validatorId, validator, validatorRule.message); } } } if (validator) { if (async && this.asyncValidatorDebounceTime) { const oldValidator = validator; validator = (control: AbstractControl): Observable<ValidationErrors | null> => { return timer(this.asyncValidatorDebounceTime).pipe( switchMap(() => { return oldValidator(control); }) ); }; } resultFns.push(validator); this._messageOpts[validatorId] = validatorRule; } // else { // // TODO: 抛出错误 // } }); return resultFns as AsyncValidatorFn[] | ValidatorFn[]; } private _translateRulesToObject(rules: DValidateRules) { if (Array.isArray(rules)) { return { validators: rules, }; } return rules; } private _findNgValidatorInDefault(validatorRule: DValidateRule) { for (const key in dDefaultValidators) { if (validatorRule.hasOwnProperty(key)) { return { id: key, ngValidator: this._generateValidatorFnFromDefault(key, validatorRule[key]) }; } } return null; } private _generateValidatorFnFromDefault(key, value) { if (typeof value === 'boolean' && value) { // boolean无需再执行函数进行传值 return dDefaultValidators[key]; } else if (typeof value !== 'boolean') { return dDefaultValidators[key](value); } return null; } private _transformRuleToNgValidator(id, validatorFn, message) { return (control: AbstractControl): ValidationErrors | null => { const res = validatorFn(control.value); return this._transValidatorResultToNgError(id, res, message); }; } private _transformRuleToNgAsyncValidator(id, validator, message) { return (control: AbstractControl): Observable<ValidationErrors | null> => { return (validator(control.value) as Observable<boolean>).pipe( map((res) => { return this._transValidatorResultToNgError(id, res, message); }) ); }; } private _transValidatorResultToNgError(id: string, res: boolean | string | null, message: string) { let error = null; if (typeof res === 'boolean' && !res) { error = {}; error[id] = message; } else if (typeof res === 'string' || (res && typeof res === 'object')) { // 兼容国际化词条 error = {}; error[id] = res; } return error; } private _autoGetIdFromRule(rule: DValidateRule | DAsyncValidateRule) { for (const key in rule) { if (!(key in ruleReservedWords)) { return key; } } return rule.id || null; } // TODO: 考虑自定义函数返回多种key场景 get dClassError() { if (this._errorStrategy === 'dirty') { return this._cd.control ? this._cd.control.invalid && this._cd.control.dirty : false; } else { return this._cd.control ? this._cd.control.invalid : false; } } get showError() { return this.dClassError; } get showStatus() { if (this._errorStrategy === 'dirty') { return this._cd.control ? this._cd.control.dirty : false; } else { return true; } } get dClassSuccess() { // COMMENT: 暂不默认提供 if (this._rules['errorStrategy'] === 'dirty') { return this._cd.control ? this._cd.control.valid && this._cd.control.dirty : false; } else if (!this._rules['errorStrategy']) { return false; } else { return this._cd.control ? this._cd.control.valid : false; } } get dClassWarning() { return this._warning ? true : false; } get invalid() { return this._cd.control ? this._cd.control.invalid : false; } private _registerOnStatusChange() { if (this._cd && this._cd.control) { this._cd.control.statusChanges.subscribe((status) => { this._parseErrors(this._cd.control.errors); this._updateParent(); // update error message to parent directive this.updateStatusAndMessageToView(status); }); this._registered = true; } } private _parseErrors(errors: { [key: string]: any }): void { if (!errors) { this._errorMessage = null; } else { /* if a rule did not have a message, we will try to get a message from errors by id */ const { resId, resRule } = this._getARuleByErrors(errors); this._errorStrategy = this._getErrorStrategy(resRule); this._errorMessage = resRule && (resRule.message || this._getMessageFormErrorsById(errors, resId) || this._getDefaultErrorMessage(resRule, resId) || (this._rules as { message: string }).message); } this.dRulesStatusChange.emit({ showError: this.showError, errorMessage: this._errorMessage, errors: errors, }); } private _getDefaultErrorMessage(rule, id) { return rule && rule[id] && this.i18nFormText[id] && this.i18nFormText[id](rule[id]); } private _getErrorStrategy(rule?) { return (rule && rule.errorStrategy) || this._rules['errorStrategy'] || 'dirty'; } private _getMessageFormErrorsById(errors: { [key: string]: any }, id: string): string | null { if (errors[id] && typeof errors[id] === 'string') { return errors[id]; } else if (errors[id] && typeof errors[id] === 'object' && (errors[id][this.locale] || errors[id]['default'])) { return errors[id]; } else { return null; } } private _getARuleByErrors(errors: { [key: string]: any }) { // TODO:处理errors为null let resId: string; let resRule = null; for (const key of Object.keys(errors)) { if (this._messageOpts[key]) { if (resRule) { const priority = resRule.priority || 0; if (this._messageOpts[key].priority && this._messageOpts[key].priority > priority) { resId = key; resRule = this._messageOpts[key]; } } else { resId = key; resRule = this._messageOpts[key]; } } } return { resId: resId, resRule: resRule }; } _updateParent() { if (this._parent) { // TODO } } private _setUpdateStrategy(): void { if (!Array.isArray(this._rules) && typeof this._rules === 'object' && this._rules.updateOn) { (this._cd.control as any)._updateOn = this._rules.updateOn; } } public _updateValueAndValidity() { if (this._cd && this._cd.control) { this._cd.control.updateValueAndValidity(); } } private _updateValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void { if (this._cd && this._cd.control) { this._cd.control.setValidators(newValidator); } } private _updateAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void { if (this._cd && this._cd.control) { this._cd.control.setAsyncValidators(newValidator); } } abstract updateStatusAndMessageToView(status: any): void; } const dControlErrorStatusHost = { '[class.devui-error]': 'dClassError', '[class.devui-success]': 'dClassSuccess', '[class.devui-warning]': 'dClassWarning', }; @Directive({ selector: `[dValidateRules][formGroupName],[dValidateRules][formArrayName],[dValidateRules][ngModelGroup], [dValidateRules][formGroup],[dValidateRules]form:not([ngNoForm]),[dValidateRules][ngForm]`, /* eslint-disable-next-line @angular-eslint/no-host-metadata-property*/ host: dControlErrorStatusHost, exportAs: 'dValidateRules', }) export class DFormGroupRuleDirective extends DAbstractControlRuleDirective implements OnInit, OnChanges, OnDestroy { @Input('dValidateRules') rules: DValidateRules; @Output() dRulesStatusChange: EventEmitter<any> = new EventEmitter<any>(); private destroy$ = new Subject(); constructor(@Self() cd: ControlContainer, @Optional() @Host() @SkipSelf() parentDir: DFormGroupRuleDirective, private i18n: I18nService) { super(cd, parentDir); } ngOnInit(): void { this.i18nFormText = this.i18n.getI18nText().form; this.locale = this.i18n.getI18nText().locale; this.i18n .langChange() .pipe(takeUntil(this.destroy$)) .subscribe((data: I18nInterface) => { this.i18nFormText = data.form; this.locale = data.locale; }); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } setErrorMessageByChild(msg: string) { if (!this.errorMessage) { this.errorMessage = msg; } } updateStatusAndMessageToView(status: any): void { // do nothing } } @Directive({ selector: '[dValidateRules][formControlName],[dValidateRules][ngModel],[dValidateRules][formControl]', /* eslint-disable-next-line @angular-eslint/no-host-metadata-property*/ host: dControlErrorStatusHost, exportAs: 'dValidateRules', }) export class DFormControlRuleDirective extends DAbstractControlRuleDirective implements OnInit, OnChanges, OnDestroy { @Input('dValidateRules') rules: DValidateRules; @Output() dRulesStatusChange: EventEmitter<any> = new EventEmitter<any>(); @Input('dValidatePopConfig') popConfig: DPopConfig; popoverComponentRef: ComponentRef<PopoverComponent>; private destroy$ = new Subject(); popMessage: string; // 最终显示的message get showType() { return (this.fullRules as { messageShowType: string }).messageShowType || 'popover'; } get popPosition() { return (this.fullRules as { popPosition: any }).popPosition || ['right', 'bottom']; } constructor( @Self() cd: NgControl, @Optional() @Host() private dFormItem: FormItemComponent, @Optional() @Host() @SkipSelf() parentDir: DFormGroupRuleDirective, private i18n: I18nService, public triggerElementRef: ElementRef, private overlayContainerRef: OverlayContainerRef, private componentFactoryResolver: ComponentFactoryResolver ) { super(cd, parentDir); } ngOnInit(): void { this.setI18nText(); this._registerFocusChange(); } setI18nText() { this.i18nFormText = this.i18n.getI18nText().form; this.locale = this.i18n.getI18nText().locale; this.i18n .langChange() .pipe(takeUntil(this.destroy$)) .subscribe((data: I18nInterface) => { this.i18nFormText = data.form; this.locale = data.locale; }); } _registerFocusChange() { merge(fromEvent(this.triggerElementRef.nativeElement, 'focusin'), fromEvent(this.triggerElementRef.nativeElement, 'focusout')) .pipe(takeUntil(this.destroy$)) .subscribe((event: Event) => { if (event.type === 'focusin') { this.showPopMessage(); } if (event.type === 'focusout') { this.hidePopMessage(); } }); } _updateFormContainer(status, message: string): void { if (this.dFormItem) { this.dFormItem.updateFeedback(status, message); } } _updatePopMessage(status: DFormControlStatus, message: string): void { this.popMessage = status === 'error' ? message : null; // 暂不提供除errorMessage外提示 if (this.popoverComponentRef) { this.hidePopMessage(); this.showPopMessage(); } } updateStatusAndMessageToView(status: any): void { let controlStatus = null; let message = null; if (this.showStatus) { [controlStatus, message] = this.getFormControlStatusAndMessage(status); } /* 国际化适配 */ if (message && typeof message === 'object') { message = message[this.locale] || message['default'] || null; } if (this.showType === 'popover') { this._updatePopMessage(controlStatus, message); this._updateFormContainer(controlStatus, null); } else if (this.showType === 'text') { this._updateFormContainer(controlStatus, message); } } getFormControlStatusAndMessage(ngStatus: any) { let status = null; let message = null; if (ngStatus === 'INVALID') { status = 'error'; message = this.errorMessage; } else if (ngStatus === 'PENDING') { status = 'pending'; } else if (ngStatus === 'VALID') { status = 'success'; } return [status, message]; } createPopover(type: 'error' | 'warning', content: string) { this.popoverComponentRef = this.overlayContainerRef.createComponent( this.componentFactoryResolver.resolveComponentFactory(PopoverComponent) ); Object.assign(this.popoverComponentRef.instance, { content: content, triggerElementRef: this.triggerElementRef, position: this.popPosition, popType: type, popMaxWidth: this.popConfig?.popMaxWidth || 200, appendToBody: true, zIndex: this.popConfig?.zIndex || 1060, }); } public showPopMessage() { this.showPop('error', this.popMessage); if (this.popMessage) { this._updateFormContainer(null, null); } } public hidePopMessage() { this.hidePop(); if (this.popMessage) { this._updateFormContainer(this.showError ? 'error' : null, null); } } showPop(type, message) { this.hidePop(); this.createPopover(type, message); } hidePop() { if (this.popoverComponentRef) { this.destroyPop(); } } destroyPop() { if (this.popoverComponentRef) { this.popoverComponentRef.destroy(); this.popoverComponentRef = null; } } ngOnDestroy(): void { this.destroyPop(); this.destroy$.next(); this.destroy$.complete(); } }
the_stack
import { Component, Property, NotifyPropertyChanges, Internationalization, ModuleDeclaration } from '@syncfusion/ej2-base'; import { EmitType, INotifyPropertyChanged, setCulture, Browser } from '@syncfusion/ej2-base'; import { Event, EventHandler, Complex, Collection, isNullOrUndefined, remove, createElement } from '@syncfusion/ej2-base'; import { Border, Font, Container, Margin, Annotation, TooltipSettings } from './model/base'; import { FontModel, BorderModel, ContainerModel, MarginModel, AnnotationModel, TooltipSettingsModel } from './model/base-model'; import { AxisModel } from './axes/axis-model'; import { Axis, Pointer } from './axes/axis'; import { load, loaded, gaugeMouseMove, gaugeMouseLeave, gaugeMouseDown, gaugeMouseUp, resized, valueChange } from './model/constant'; import { LinearGaugeModel } from './linear-gauge-model'; import { ILoadedEventArgs, ILoadEventArgs, IAnimationCompleteEventArgs, IAnnotationRenderEventArgs } from './model/interface'; import { ITooltipRenderEventArgs, IVisiblePointer, IMouseEventArgs, IAxisLabelRenderEventArgs, IMoveCursor } from './model/interface'; import { IResizeEventArgs, IValueChangeEventArgs, IThemeStyle, IPrintEventArgs, IPointerDragEventArgs } from './model/interface'; import { Size, valueToCoefficient, calculateShapes, stringToNumber, removeElement, getElement, VisibleRange, getExtraWidth } from './utils/helper'; import { measureText, Rect, TextOption, textElement, GaugeLocation, RectOption, PathOption } from './utils/helper'; import { getBox, withInRange, getPointer, convertPixelToValue, isPointerDrag } from './utils/helper'; import { Orientation, LinearGaugeTheme, LabelPlacement } from './utils/enum'; import { dragEnd, dragMove, dragStart } from './model/constant'; import { AxisLayoutPanel } from './axes/axis-panel'; import { SvgRenderer } from '@syncfusion/ej2-svg-base'; import { AxisRenderer } from './axes/axis-renderer'; import { Annotations } from './annotations/annotations'; import { GaugeTooltip } from './user-interaction/tooltip'; import { getThemeStyle } from './model/theme'; import { PdfPageOrientation } from '@syncfusion/ej2-pdf-export'; import { ExportType } from '../linear-gauge/utils/enum'; import { Print } from './model/print'; import { PdfExport } from './model/pdf-export'; import { ImageExport } from './model/image-export'; import { Gradient } from './axes/gradient'; /** * Represents the EJ2 Linear gauge control. * ```html * <div id="container"/> * <script> * var gaugeObj = new LinearGauge({ }); * gaugeObj.appendTo("#container"); * </script> * ``` */ @NotifyPropertyChanges export class LinearGauge extends Component<HTMLElement> implements INotifyPropertyChanged { //Module declaration for gauge /** * Specifies the module that is used to place any text or images as annotation into the linear gauge. */ public annotationsModule: Annotations; /** * Specifies the module that is used to display the pointer value in tooltip. */ public tooltipModule: GaugeTooltip; /** * This module enables the print functionality in linear gauge control. * * @private */ public printModule: Print; /** * This module enables the export to PDF functionality in linear gauge control. * * @private */ public pdfExportModule: PdfExport; /** * This module enables the export to image functionality in linear gauge control. * * @private */ public imageExportModule: ImageExport; /** * This module enables the gradient option for pointer and ranges. * * @private */ public gradientModule: Gradient; /** * Specifies the gradient count of the linear gauge. * * @private */ public gradientCount: number = 0; /** * Specifies the width of the linear gauge as a string in order to provide input as both like '100px' or '100%'. * If specified as '100%, gauge will render to the full width of its parent element. * * @default null */ @Property(null) public width: string; /** * Enables or disables the gauge to be rendered to the complete width. * * @default true */ @Property(true) public allowMargin: boolean; /** * Specifies the height of the linear gauge as a string in order to provide input as both like '100px' or '100%'. * If specified as '100%, gauge will render to the full height of its parent element. * * @default null */ @Property(null) public height: string; /** * Specifies the orientation of the rendering of the linear gauge. * * @default Vertical */ @Property('Vertical') public orientation: Orientation; /** * Specifies the placement of the label in linear gauge. * * @default None */ @Property('None') public edgeLabelPlacement: LabelPlacement; /** * Enables or disables the print functionality in linear gauge. * * @default false */ @Property(false) public allowPrint: boolean; /** * Enables or disables the export to image functionality in linear gauge. * * @default false */ @Property(false) public allowImageExport: boolean; /** * Enables or disables the export to PDF functionality in linear gauge. * * @default false */ @Property(false) public allowPdfExport: boolean; /** * Specifies the options to customize the margins of the linear gauge. */ @Complex<MarginModel>({}, Margin) public margin: MarginModel; /** * Specifies the options for customizing the color and width of the border for linear gauge. */ @Complex<BorderModel>({ color: '', width: 0 }, Border) public border: BorderModel; /** * Specifies the background color of the gauge. This property accepts value in hex code, rgba string as a valid CSS color string. * * @default 'transparent' */ @Property(null) public background: string; /** * Specifies the title for linear gauge. */ @Property('') public title: string; /** * Specifies the options for customizing the appearance of title for linear gauge. */ @Complex<FontModel>({ size: '15px', color: null, fontStyle: null, fontWeight: null }, Font) public titleStyle: FontModel; /** * Specifies the options for customizing the container in linear gauge. */ @Complex<ContainerModel>({}, Container) public container: ContainerModel; /** * Specifies the options for customizing the axis in linear gauge. */ @Collection<AxisModel>([{}], Axis) public axes: AxisModel[]; /** * Specifies the options for customizing the tooltip in linear gauge. */ @Complex<TooltipSettingsModel>({}, TooltipSettings) public tooltip: TooltipSettingsModel; /** * Specifies the options for customizing the annotation of linear gauge. */ @Collection<AnnotationModel>([{}], Annotation) public annotations: AnnotationModel[]; /** * Specifies the color palette for axis ranges in linear gauge. * * @default [] */ @Property([]) public rangePalettes: string[]; /** * Enables or disables a grouping separator should be used for a number. * * @default false */ @Property(false) public useGroupingSeparator: boolean; /** * Specifies the description for linear gauge. * * @default null */ @Property(null) public description: string; /** * Specifies the tab index value for the linear gauge. * * @default 1 */ @Property(1) public tabIndex: number; /** * Specifies the format to apply for internationalization in linear gauge. * * @default null */ @Property(null) public format: string; /** * Specifies the theme supported for the linear gauge. * * @default Material */ @Property('Material') public theme: LinearGaugeTheme; /** * Triggers after the gauge gets rendered. * * @event */ @Event() public loaded: EmitType<ILoadedEventArgs>; /** * Triggers before the gauge gets rendered. * * @event */ @Event() public load: EmitType<ILoadEventArgs>; /** * Triggers after completing the animation for pointer. * * @event */ @Event() public animationComplete: EmitType<IAnimationCompleteEventArgs>; /** * Triggers before each axis label gets rendered. * * @event */ @Event() public axisLabelRender: EmitType<IAxisLabelRenderEventArgs>; /** * Triggers before the pointer is dragged. * * @event */ @Event() public dragStart: EmitType<IPointerDragEventArgs>; /** * Triggers while dragging the pointers. * * @event */ @Event() public dragMove: EmitType<IPointerDragEventArgs>; /** * Triggers after the pointer is dragged. * * @event */ @Event() public dragEnd: EmitType<IPointerDragEventArgs>; /** * Triggers before each annotation gets rendered. * * @event */ @Event() public annotationRender: EmitType<IAnnotationRenderEventArgs>; /** * Triggers before the tooltip get rendered. * * @event * @deprecated */ @Event() public tooltipRender: EmitType<ITooltipRenderEventArgs>; /** * Triggers when performing the mouse move operation on gauge area. * * @event */ @Event() public gaugeMouseMove: EmitType<IMouseEventArgs>; /** * Triggers when performing the mouse leave operation from the gauge area. * * @event */ @Event() public gaugeMouseLeave: EmitType<IMouseEventArgs>; /** * Triggers when performing the mouse down operation on gauge area. * * @event */ @Event() public gaugeMouseDown: EmitType<IMouseEventArgs>; /** * Triggers when performing mouse up operation on gauge area. * * @event */ @Event() public gaugeMouseUp: EmitType<IMouseEventArgs>; /** * Triggers while changing the value of the pointer by UI interaction. * * @event */ @Event() public valueChange: EmitType<IValueChangeEventArgs>; /** * Triggers after window resize. * * @event */ @Event() public resized: EmitType<IResizeEventArgs>; /** * Triggers before the prints gets started. * * @event */ @Event() public beforePrint: EmitType<IPrintEventArgs>; /** @private */ public activePointer: Pointer; /** @private */ public activeAxis: Axis; /** @private */ public renderer: SvgRenderer; /** @private */ public svgObject: Element; /** @private */ public availableSize: Size; /** @private */ public actualRect: Rect; /** @private */ public intl: Internationalization; /** @private* */ public containerBounds: Rect; /** @private */ public isTouch: boolean; /** @private */ public isDrag: boolean = false; /** * @private * Calculate the axes bounds for gauge. * @hidden */ public gaugeAxisLayoutPanel: AxisLayoutPanel; /** * @private * Render the axis elements for gauge. * @hidden */ public axisRenderer: AxisRenderer; /** @private */ private resizeTo: number; /** @private */ public containerObject: Element; /** @private */ public pointerDrag: boolean = false; /** @private */ public mouseX: number = 0; /** @private */ public mouseY: number = 0; /** @private */ public mouseElement: Element; /** @private */ public gaugeResized: boolean = false; /** @private */ public nearSizes: number[]; /** @private */ public farSizes: number[]; /** * @private */ public themeStyle: IThemeStyle; /** * @private * Constructor for creating the widget * @hidden */ // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility constructor(options?: LinearGaugeModel, element?: string | HTMLElement) { super(options, element); } /** * Initialize the preRender method. */ protected preRender(): void { this.unWireEvents(); this.trigger(load, { gauge: this }); this.initPrivateVariable(); this.setCulture(); this.createSvg(); this.wireEvents(); } private setTheme(): void { this.themeStyle = getThemeStyle(this.theme); } private initPrivateVariable(): void { if (this.element.id === '') { const collection: number = document.getElementsByClassName('e-lineargauge').length; this.element.id = 'lineargauge_' + 'control_' + collection; } this.renderer = new SvgRenderer(this.element.id); this.gaugeAxisLayoutPanel = new AxisLayoutPanel(this); this.axisRenderer = new AxisRenderer(this); } /** * Method to set culture for chart */ private setCulture(): void { this.intl = new Internationalization(); } /** * Methods to create svg element */ private createSvg(): void { this.removeSvg(); this.calculateSize(); this.svgObject = this.renderer.createSvg({ id: this.element.id + '_svg', width: this.availableSize.width, height: this.availableSize.height }); } /** * To Remove the SVG. * * @return {boolean} * @private */ public removeSvg(): void { removeElement(this.element.id + '_Secondary_Element'); if (!(isNullOrUndefined(this.svgObject)) && !isNullOrUndefined(this.svgObject.parentNode)) { remove(this.svgObject); } this.clearTemplate(); } /** * Method to calculate the size of the gauge */ private calculateSize(): void { const width: number = stringToNumber(this.width, this.element.offsetWidth) || this.element.offsetWidth || 600; const height: number = stringToNumber(this.height, this.element.offsetHeight) || this.element.offsetHeight || 450; this.availableSize = new Size(width, height); } private renderElements(): void { this.setTheme(); this.renderGaugeElements(); this.calculateBounds(); this.renderAxisElements(); this.renderComplete(); } /** * To Initialize the control rendering */ protected render(): void { this.renderElements(); } /** * @private * To render the gauge elements */ public renderGaugeElements(): void { this.appendSecondaryElement(); this.renderBorder(); this.renderTitle(); this.renderContainer(); } private appendSecondaryElement(): void { if (isNullOrUndefined(getElement(this.element.id + '_Secondary_Element'))) { const secondaryElement: Element = createElement('div'); secondaryElement.id = this.element.id + '_Secondary_Element'; secondaryElement.setAttribute('style', 'position: relative'); this.element.appendChild(secondaryElement); } } /** * Render the map area border */ private renderArea(): void { const size: Size = measureText(this.title, this.titleStyle); const rectSize: Rect = new Rect( this.actualRect.x, this.actualRect.y - (size.height / 2), this.actualRect.width, this.actualRect.height); const rect: RectOption = new RectOption( this.element.id + 'LinearGaugeBorder', this.background || this.themeStyle.backgroundColor, this.border, 1, rectSize); this.svgObject.appendChild(this.renderer.drawRectangle(rect) as SVGRectElement); } /** * @private * To calculate axes bounds */ public calculateBounds(): void { this.gaugeAxisLayoutPanel.calculateAxesBounds(); } /** * @private * To render axis elements */ public renderAxisElements(): void { this.axisRenderer.renderAxes(); this.element.appendChild(this.svgObject); if (this.annotationsModule) { this.annotationsModule.renderAnnotationElements(); } this.trigger(loaded, { gauge: this }); removeElement('gauge-measuretext'); } private renderBorder(): void { const width: number = this.border.width; if (width > 0 || (this.background || this.themeStyle.backgroundColor)) { const rect: RectOption = new RectOption( this.element.id + '_LinearGaugeBorder', this.background || this.themeStyle.backgroundColor, this.border, 1, new Rect(width / 2, width / 2, this.availableSize.width - width, this.availableSize.height - width), null, null); this.svgObject.appendChild(this.renderer.drawRectangle(rect) as HTMLElement); } } private renderTitle(): void { const size: Size = measureText(this.title, this.titleStyle); const options: TextOption = new TextOption( this.element.id + '_LinearGaugeTitle', this.availableSize.width / 2, this.margin.top + (size.height / 2), 'middle', this.title ); const titleBounds: Rect = { x: options.x - (size.width / 2), y: options.y, width: size.width, height: size.height }; const x: number = this.margin.left; const y: number = (isNullOrUndefined(titleBounds)) ? this.margin.top : titleBounds.y; const height: number = (this.availableSize.height - y - this.margin.bottom); const width: number = (this.availableSize.width - this.margin.left - this.margin.right); this.actualRect = { x: x, y: y, width: width, height: height }; if (this.title) { this.titleStyle.fontFamily = this.themeStyle.fontFamily || this.titleStyle.fontFamily; this.titleStyle.size = this.themeStyle.fontSize || this.titleStyle.size; this.titleStyle.fontStyle = this.titleStyle.fontStyle || this.themeStyle.titleFontStyle; this.titleStyle.fontWeight = this.titleStyle.fontWeight || this.themeStyle.titleFontWeight; const element: Element = textElement( options, this.titleStyle, this.titleStyle.color || this.themeStyle.titleFontColor, this.svgObject ); element.setAttribute('aria-label', this.description || this.title); element.setAttribute('tabindex', this.tabIndex.toString()); } } /* * Method to unbind the gauge events */ private unWireEvents(): void { EventHandler.remove(this.element, Browser.touchStartEvent, this.gaugeOnMouseDown); EventHandler.remove(this.element, Browser.touchMoveEvent, this.mouseMove); EventHandler.remove(this.element, Browser.touchEndEvent, this.mouseEnd); EventHandler.remove(this.element, 'contextmenu', this.gaugeRightClick); EventHandler.remove( this.element, (Browser.isPointer ? 'pointerleave' : 'mouseleave'), this.mouseLeave ); EventHandler.remove( <HTMLElement & Window>window, (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.gaugeResize.bind(this) ); } /* * Method to bind the gauge events */ private wireEvents(): void { /*! Bind the Event handler */ EventHandler.add(this.element, Browser.touchStartEvent, this.gaugeOnMouseDown, this); EventHandler.add(this.element, Browser.touchMoveEvent, this.mouseMove, this); EventHandler.add(this.element, Browser.touchEndEvent, this.mouseEnd, this); EventHandler.add(this.element, 'contextmenu', this.gaugeRightClick, this); EventHandler.add( this.element, (Browser.isPointer ? 'pointerleave' : 'mouseleave'), this.mouseLeave, this ); EventHandler.add( <HTMLElement & Window>window, (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.gaugeResize, this ); this.setStyle(<HTMLElement>this.element); } private setStyle(element: HTMLElement): void { element.style.touchAction = isPointerDrag(this.axes) ? 'none' : 'element'; element.style.msTouchAction = isPointerDrag(this.axes) ? 'none' : 'element'; element.style.msContentZooming = 'none'; element.style.msUserSelect = 'none'; element.style.webkitUserSelect = 'none'; element.style.position = 'relative'; } /** * Handles the gauge resize. * * @return {boolean} * @private */ public gaugeResize(e: Event): boolean { const args: IResizeEventArgs = { gauge: this, previousSize: new Size( this.availableSize.width, this.availableSize.height ), name: resized, currentSize: new Size(0, 0) }; if (this.resizeTo) { clearTimeout(this.resizeTo); } if (!isNullOrUndefined(this.element) && this.element.classList.contains('e-lineargauge')) { this.resizeTo = window.setTimeout( (): void => { this.createSvg(); args.currentSize = new Size(this.availableSize.width, this.availableSize.height); this.trigger(resized, args); this.renderElements(); }, 500); } return false; } /** * To destroy the gauge element from the DOM. */ public destroy(): void { this.unWireEvents(); this.removeSvg(); super.destroy(); } /** * @private * To render the gauge container */ public renderContainer(): void { let width: number; let height: number; let x: number; let y: number; let options: PathOption; const labelPadding: number = 20; const extraPadding: number = 30; let path: string = ''; const fill: string = (this.container.backgroundColor !== 'transparent' || (this.theme !== 'Bootstrap4' && this.theme !== 'Material')) ? this.container.backgroundColor : this.themeStyle.containerBackground; let rect: RectOption; const radius: number = this.container.width; const bottomRadius: number = radius + ((radius / 2) / Math.PI); const topRadius: number = radius / 2; let allowContainerRender: boolean = false; for (let i = 0; i < this.axes.length; i++) { if (this.axes[i].minimum !== this.axes[i].maximum) { allowContainerRender = true; break; } } if (this.orientation === 'Vertical') { if (this.allowMargin) { height = this.actualRect.height; height = (this.container.height > 0) ? this.container.height : ((height / 2) - ((height / 2) / 4)) * 2; height = (this.container.type === 'Thermometer') ? height - (bottomRadius * 2) - topRadius : height; } else { height = this.actualRect.height - labelPadding - extraPadding; height = (this.container.type === 'Thermometer') ? (radius !== 0) ? (this.actualRect.height - (bottomRadius * 2) - topRadius - extraPadding) : height : height; } width = this.container.width; x = (this.actualRect.x + ((this.actualRect.width / 2) - (this.container.width / 2))) + this.container.offset; y = this.actualRect.y + ((this.actualRect.height / 2) - ((this.container.type === 'Thermometer') ? ((height + (bottomRadius * 2) - topRadius)) / 2 : height / 2)); } else { if (this.allowMargin) { width = (this.container.height > 0) ? this.container.height : ((this.actualRect.width / 2) - ((this.actualRect.width / 2) / 4)) * 2; width = (this.container.type === 'Thermometer') ? width - (bottomRadius * 2) - topRadius : width; } else { width = this.actualRect.width - labelPadding; width = (this.container.type === 'Thermometer') ? (this.actualRect.width - (bottomRadius * 2) - topRadius) : width; } x = this.actualRect.x + ((this.actualRect.width / 2) - ((this.container.type === 'Thermometer') ? (width - (bottomRadius * 2) + topRadius) / 2 : width / 2)); y = (this.actualRect.y + ((this.actualRect.height / 2) - (this.container.width / 2))) + this.container.offset; height = this.container.width; } this.containerBounds = (!allowContainerRender) ? { x: 0, y: 0, width: 0, height: 0 } : { x: x, y: y, width: width, height: height }; if ((this.containerBounds.width > 0 && this.orientation === 'Vertical') || (this.containerBounds.height > 0 && this.orientation === 'Horizontal')) { this.containerObject = this.renderer.createGroup({ id: this.element.id + '_Container_Group', transform: 'translate( 0, 0)' }); if (this.container.type === 'Normal') { let containerBorder: BorderModel = { color: this.container.border.color || this.themeStyle.containerBorderColor, width: this.container.border.width, dashArray: this.container.border.dashArray }; rect = new RectOption( this.element.id + '_' + this.container.type + '_Layout', fill, containerBorder, 1, new Rect(x, y, width, height)); this.containerObject.appendChild(this.renderer.drawRectangle(rect)); } else { path = getBox( this.containerBounds, this.container.type, this.orientation, new Size(this.container.height, this.container.width), 'container', null, null, this.container.roundedCornerRadius); options = new PathOption( this.element.id + '_' + this.container.type + '_Layout', fill, this.container.border.width, this.container.border.color || this.themeStyle.containerBorderColor, 1, this.container.border.dashArray, path); this.containerObject.appendChild(this.renderer.drawPath(options) as SVGAElement); } this.svgObject.appendChild(this.containerObject); } } /** * Method to set mouse x, y from events */ private setMouseXY(e: PointerEvent): void { let pageX: number; let pageY: number; const svgRect: ClientRect = getElement(this.element.id + '_svg').getBoundingClientRect(); const rect: ClientRect = this.element.getBoundingClientRect(); if (e.type.indexOf('touch') > -1) { this.isTouch = true; const touchArg: TouchEvent = <TouchEvent & PointerEvent>e; pageY = touchArg.changedTouches[0].clientY; pageX = touchArg.changedTouches[0].clientX; } else { this.isTouch = e.pointerType === 'touch' || e.pointerType === '2'; pageX = e.clientX; pageY = e.clientY; } this.mouseY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0); this.mouseX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0); } /** * Handles the mouse down on gauge. * * @return {boolean} * @private */ public gaugeOnMouseDown(e: PointerEvent): boolean { let pageX: number; let pageY: number; let target: Element; const element: Element = <Element>e.target; const split: string[] = []; const clientRect: ClientRect = this.element.getBoundingClientRect(); let axis: Axis; const isPointer: boolean = false; let pointer: Pointer; let current: IMoveCursor; let currentPointer: IVisiblePointer; this.setMouseXY(e); let top: number; let left: number; let pointerElement: Element; let svgPath: SVGPathElement; const dragProcess: boolean = false; const args: IMouseEventArgs = this.getMouseArgs(e, 'touchstart', gaugeMouseDown); this.trigger(gaugeMouseDown, args, (observedArgs: IMouseEventArgs) => { this.mouseX = args.x; this.mouseY = args.y; if (args.target) { if (!args.cancel && ((args.target.id.indexOf('MarkerPointer') > -1) || (args.target.id.indexOf('BarPointer') > -1))) { current = this.moveOnPointer(args.target as HTMLElement); currentPointer = getPointer(args.target as HTMLElement, this); this.activeAxis = <Axis>this.axes[currentPointer.axisIndex]; this.activePointer = <Pointer>this.activeAxis.pointers[currentPointer.pointerIndex]; if (isNullOrUndefined(this.activePointer.pathElement)) { this.activePointer.pathElement = [e.target as Element]; } const pointInd: number = parseInt(this.activePointer.pathElement[0].id.slice(-1), 10); const axisInd: number = parseInt(this.activePointer.pathElement[0].id.match(/\d/g)[0], 10); if (currentPointer.pointer.enableDrag) { this.trigger(dragStart, { axis: this.activeAxis, name: dragStart, pointer: this.activePointer, currentValue: this.activePointer.currentValue, pointerIndex: pointInd, axisIndex: axisInd } as IPointerDragEventArgs); } if (!isNullOrUndefined(current) && current.pointer) { this.pointerDrag = true; this.mouseElement = args.target; this.svgObject.setAttribute('cursor', current.style); this.mouseElement.setAttribute('cursor', current.style); } } } }); return false; } /** * Handles the mouse move. * * @return {boolean} * @private */ public mouseMove(e: PointerEvent): boolean { let current: IMoveCursor; let element: Element; this.setMouseXY(e); const args: IMouseEventArgs = this.getMouseArgs(e, 'touchmove', gaugeMouseMove); this.trigger(gaugeMouseMove, args, (observedArgs: IMouseEventArgs) => { this.mouseX = args.x; this.mouseY = args.y; let dragArgs: IPointerDragEventArgs; if (args.target && !args.cancel) { if ((args.target.id.indexOf('MarkerPointer') > -1) || (args.target.id.indexOf('BarPointer') > -1)) { const pointerIndex: number = parseInt(args.target.id.slice(-1), 10); const axisIndex: number = parseInt(args.target.id.split('AxisIndex_')[1].match(/\d/g)[0], 10); if (this.axes[axisIndex].pointers[pointerIndex].enableDrag) { current = this.moveOnPointer(args.target as HTMLElement); if (!(isNullOrUndefined(current)) && current.pointer) { this.element.style.cursor = current.style; } if (this.activePointer) { this.isDrag = true; const dragPointInd: number = parseInt(this.activePointer.pathElement[0].id.slice(-1), 10); const dragAxisInd: number = parseInt(this.activePointer.pathElement[0].id.match(/\d/g)[0], 10); dragArgs = { axis: this.activeAxis, pointer: this.activePointer, previousValue: this.activePointer.currentValue, name: dragMove, currentValue: null, axisIndex: dragAxisInd, pointerIndex: dragPointInd }; if (args.target.id.indexOf('MarkerPointer') > -1) { this.markerDrag(this.activeAxis, (this.activeAxis.pointers[dragPointInd]) as Pointer); } else { this.barDrag(this.activeAxis, (this.activeAxis.pointers[dragPointInd]) as Pointer); } dragArgs.currentValue = this.activePointer.currentValue; this.trigger(dragMove, dragArgs); } } } else { this.element.style.cursor = (this.pointerDrag) ? this.element.style.cursor : 'auto'; } this.gaugeOnMouseMove(e); } }); this.notify(Browser.touchMoveEvent, e); return false; } /** * To find the mouse move on pointer. * * @param element */ private moveOnPointer(element: HTMLElement): IMoveCursor { const clientRect: ClientRect = this.element.getBoundingClientRect(); let isPointer: boolean = false; let top: number; let left: number; const pointerElement: Element = getElement(element.id); const svgPath: SVGPathElement = <SVGPathElement>pointerElement; let cursorStyle: string; let process: IMoveCursor; const current: IVisiblePointer = getPointer(element as HTMLElement, this); const axis: Axis = current.axis; const pointer: Pointer = current.pointer; if (pointer.enableDrag) { if (pointer.type === 'Bar') { if (this.orientation === 'Vertical') { top = pointerElement.getBoundingClientRect().top - clientRect.top; top = (!axis.isInversed) ? top : top + svgPath.getBBox().height; isPointer = !axis.isInversed ? (this.mouseY < (top + 10) && this.mouseY >= top) : (this.mouseY <= top && this.mouseY > (top - 10)); cursorStyle = 'grabbing'; } else { left = pointerElement.getBoundingClientRect().left - clientRect.left; left = (!axis.isInversed) ? left + svgPath.getBBox().width : left; isPointer = !axis.isInversed ? (this.mouseX > (left - 10) && this.mouseX <= left) : (this.mouseX >= left && this.mouseX < (left + 10)); cursorStyle = 'grabbing'; } } else { isPointer = true; cursorStyle = 'grabbing'; } } if (isPointer) { process = { pointer: isPointer, style: cursorStyle }; } return process; } /** * @private * Handle the right click * @param event */ public gaugeRightClick(event: MouseEvent | PointerEvent): boolean { if (event.buttons === 2 || (<PointerEvent>event).pointerType === 'touch') { event.preventDefault(); event.stopPropagation(); return false; } return true; } /** * Handles the mouse leave. * * @return {boolean} * @private */ public mouseLeave(e: PointerEvent): boolean { let parentNode: HTMLElement; this.activeAxis = null; this.activePointer = null; this.svgObject.setAttribute('cursor', 'auto'); const args: IMouseEventArgs = this.getMouseArgs(e, 'touchmove', gaugeMouseLeave); if (!isNullOrUndefined(this.mouseElement)) { parentNode = <HTMLElement>this.element; parentNode.style.cursor = ''; this.mouseElement = null; this.pointerDrag = false; } return false; } /** * Handles the mouse move on gauge. * * @return {boolean} * @private */ public gaugeOnMouseMove(e: PointerEvent | TouchEvent): boolean { let current: IVisiblePointer; if (this.pointerDrag) { current = getPointer(this.mouseElement as HTMLElement, this); if (current.pointer.enableDrag && current.pointer.animationComplete) { this[current.pointer.type.toLowerCase() + 'Drag'](current.axis, current.pointer); } } return true; } /** * Handles the mouse up. * * @return {boolean} * @private */ public mouseEnd(e: PointerEvent): boolean { this.setMouseXY(e); let parentNode: HTMLElement; let tooltipInterval: number; const isImage: boolean = isNullOrUndefined(this.activePointer) ? false : this.activePointer.markerType === 'Image'; const isTouch: boolean = e.pointerType === 'touch' || e.pointerType === '2' || e.type === 'touchend'; const args: IMouseEventArgs = this.getMouseArgs(e, 'touchend', gaugeMouseUp); this.trigger(gaugeMouseUp, args); if (this.activeAxis && this.activePointer) { const pointerInd: number = parseInt(this.activePointer.pathElement[0].id.slice(-1), 10); const axisInd: number = parseInt(this.activePointer.pathElement[0].id.match(/\d/g)[0], 10); if (this.activePointer.enableDrag) { this.trigger(dragEnd, { name: dragEnd, axis: this.activeAxis, pointer: this.activePointer, currentValue: this.activePointer.currentValue, axisIndex: axisInd, pointerIndex: pointerInd } as IPointerDragEventArgs); if (isImage) { this.activePointer.pathElement[0].setAttribute('cursor', 'pointer'); } this.activeAxis = null; this.activePointer = null; this.isDrag = false; if (!isNullOrUndefined(this.mouseElement && !isImage)) { this.triggerDragEvent(this.mouseElement); } } } if (!isNullOrUndefined(this.mouseElement)) { parentNode = <HTMLElement>this.element; parentNode.style.cursor = ''; this.mouseElement = null; this.pointerDrag = false; } this.svgObject.setAttribute('cursor', 'auto'); this.notify(Browser.touchEndEvent, e); return true; } /** * This method handles the print functionality for linear gauge. * * @param id - Specifies the element to print the linear gauge. */ public print(id?: string[] | string | Element): void { if ((this.allowPrint) && (this.printModule)) { this.printModule.print(id); } } /** * This method handles the export functionality for linear gauge. * * @param type - Specifies the type of the export. * @param fileName - Specifies the file name for the exported file. * @param orientation - Specified the orientation for the exported pdf document. */ public export(type: ExportType, fileName: string, orientation?: PdfPageOrientation, allowDownload?: boolean): Promise<string> { if (isNullOrUndefined(allowDownload)) { allowDownload = true; } if ((type !== 'PDF') && (this.allowImageExport) && (this.imageExportModule)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return new Promise((resolve: any, reject: any) => { resolve(this.imageExportModule.export(type, fileName, allowDownload)); }); } else if ((this.allowPdfExport) && (this.pdfExportModule)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return new Promise((resolve: any, reject: any) => { resolve(this.pdfExportModule.export(type, fileName, orientation, allowDownload)); }); } return null; } /** * Handles the mouse event arguments. * * @return {IMouseEventArgs} * @private */ private getMouseArgs(e: PointerEvent, type: string, name: string): IMouseEventArgs { const rect: ClientRect = this.element.getBoundingClientRect(); const location: GaugeLocation = new GaugeLocation(-rect.left, -rect.top); const isTouch: boolean = (e.type === type); location.x += isTouch ? (<TouchEvent & PointerEvent>e).changedTouches[0].clientX : e.clientX; location.y += isTouch ? (<TouchEvent & PointerEvent>e).changedTouches[0].clientY : e.clientY; return { cancel: false, name: name, model: this, x: location.x, y: location.y, target: isTouch ? <Element>(<TouchEvent & PointerEvent>e).target : <Element>e.target }; } /** * @private * @param axis * @param pointer */ public markerDrag(axis: Axis, pointer: Pointer): void { let options: PathOption; const value: number = convertPixelToValue( this.element, this.mouseElement, this.orientation, axis, 'drag', new GaugeLocation(this.mouseX, this.mouseY)); const process: boolean = withInRange(value, null, null, axis.visibleRange.max, axis.visibleRange.min, 'pointer'); if (withInRange(value, null, null, axis.visibleRange.max, axis.visibleRange.min, 'pointer')) { options = new PathOption( 'pointerID', pointer.color || this.themeStyle.pointerColor, pointer.border.width, pointer.border.color, pointer.opacity, pointer.border.dashArray, null, ''); if (this.orientation === 'Vertical') { pointer.bounds.y = this.mouseY; } else { pointer.bounds.x = this.mouseX + getExtraWidth(this.element); } pointer.currentValue = value; options = calculateShapes( pointer.bounds, pointer.markerType, new Size(pointer.width, pointer.height), pointer.imageUrl, options, this.orientation, axis, pointer); if (pointer.markerType === 'Image') { this.mouseElement.setAttribute('x', (pointer.bounds.x - (pointer.bounds.width / 2)).toString()); this.mouseElement.setAttribute('y', (pointer.bounds.y - (pointer.bounds.height / 2)).toString()); } else if (pointer.markerType === 'Circle') { this.mouseElement.setAttribute('cx', (options.cx).toString()); this.mouseElement.setAttribute('cy', (options.cy).toString()); this.mouseElement.setAttribute('r',(options.r).toString()); } else { this.mouseElement.setAttribute('d', options.d); } } } /** * @private * @param axis * @param pointer */ public barDrag(axis: Axis, pointer: Pointer): void { const line: Rect = axis.lineBounds; const range: VisibleRange = axis.visibleRange; let isDrag: boolean; const lineHeight: number = (this.orientation === 'Vertical') ? line.height : line.width; const lineY: number = (this.orientation === 'Vertical') ? line.y : line.x; let path: string; const value1: number = ((valueToCoefficient(range.min, axis, this.orientation, range) * lineHeight) + lineY); const value2: number = ((valueToCoefficient(range.max, axis, this.orientation, range) * lineHeight) + lineY); if (this.orientation === 'Vertical') { isDrag = (!axis.isInversed) ? (this.mouseY > value2 && this.mouseY < value1) : (this.mouseY > value1 && this.mouseY < value2); if (isDrag) { if ((this.container.type === 'Normal' || this.container.width === 0) && !isNullOrUndefined(this.mouseElement)) { if (!axis.isInversed) { this.mouseElement.setAttribute('y', this.mouseY.toString()); } this.mouseElement.setAttribute('height', Math.abs(value1 - this.mouseY).toString()); } else { if (!axis.isInversed) { pointer.bounds.y = this.mouseY; } pointer.bounds.height = Math.abs(value1 - this.mouseY); } } } else { const extraWidth: number = getExtraWidth(this.element); isDrag = (!axis.isInversed) ? (this.mouseX + extraWidth > value1 && this.mouseX + extraWidth < value2) : (this.mouseX + extraWidth > value2 && this.mouseX + extraWidth < value1); if (isDrag) { if ((this.container.type === 'Normal' || this.container.width === 0) && !isNullOrUndefined(this.mouseElement)) { if (axis.isInversed) { this.mouseElement.setAttribute('x', (this.mouseX + extraWidth).toString()); } this.mouseElement.setAttribute('width', Math.abs(value1 - (this.mouseX + extraWidth)).toString()); } else { if (axis.isInversed) { pointer.bounds.x = this.mouseX + extraWidth; } pointer.bounds.width = Math.abs(value1 - (this.mouseX + extraWidth)); } } } if (isDrag && !isNullOrUndefined(this.mouseElement) && this.mouseElement.tagName === 'path') { path = getBox( pointer.bounds, this.container.type, this.orientation, new Size(pointer.bounds.width, pointer.bounds.height), 'bar', this.container.width, axis, pointer.roundedCornerRadius); this.mouseElement.setAttribute('d', path); } } /** * Triggers when drag the pointer * * @param activeElement */ private triggerDragEvent(activeElement: Element): void { const active: IVisiblePointer = getPointer(activeElement as HTMLElement, this); const value: number = convertPixelToValue( this.element, activeElement, this.orientation, active.axis, 'tooltip', null); let dragArgs: IValueChangeEventArgs = { name: 'valueChange', gauge: this, element: activeElement, axisIndex: active.axisIndex, axis: active.axis, pointerIndex: active.pointerIndex, pointer: active.pointer, value: value }; this.trigger(valueChange, dragArgs, (pointerArgs : IValueChangeEventArgs) => { this.setPointerValue(pointerArgs.axisIndex, pointerArgs.pointerIndex, pointerArgs.value); }); } /** * This method is used to set the pointer value in the linear gauge. * * @param axisIndex - Specifies the index of the axis. * @param pointerIndex - Specifies the index of the pointer. * @param value - Specifies the pointer value. */ public setPointerValue(axisIndex: number, pointerIndex: number, value: number): void { const axis: Axis = <Axis>this.axes[axisIndex]; const pointer: Pointer = <Pointer>axis.pointers[pointerIndex]; const id: string = this.element.id + '_AxisIndex_' + axisIndex + '_' + pointer.type + 'Pointer_' + pointerIndex; const pointerElement: Element = getElement(id); value = (value < axis.visibleRange.min) ? axis.visibleRange.min : ((value > axis.visibleRange.max) ? axis.visibleRange.max : value); pointer.currentValue = value; if ( (pointerElement !== null) && withInRange( pointer.currentValue, null, null, axis.visibleRange.max, axis.visibleRange.min, 'pointer' ) ) { this.gaugeAxisLayoutPanel['calculate' + pointer.type + 'Bounds'](axisIndex, axis, pointerIndex, pointer); this.axisRenderer['draw' + pointer.type + 'Pointer'](axis, axisIndex, pointer, pointerIndex, pointerElement.parentElement); } } /** * This method is used to set the annotation value in the linear gauge. * * @param annotationIndex - Specifies the index of the annotation. * @param content - Specifies the text of the annotation. */ public setAnnotationValue(annotationIndex: number, content: string, axisValue?: number): void { const elementExist: boolean = getElement(this.element.id + '_Annotation_' + annotationIndex) === null; const element: HTMLElement = <HTMLElement>getElement(this.element.id + '_AnnotationsGroup') || createElement('div', { id: this.element.id + '_AnnotationsGroup' }); const annotation: Annotation = <Annotation>this.annotations[annotationIndex]; if (content !== null) { removeElement(this.element.id + '_Annotation_' + annotationIndex); annotation.content = content; annotation.axisValue = !isNullOrUndefined(axisValue) ? axisValue : annotation.axisValue; this.annotationsModule.createAnnotationTemplate(element, annotationIndex); if (!isNullOrUndefined(annotation.axisIndex)) { const axis: Axis = <Axis>this.axes[annotation.axisIndex]; const range: VisibleRange = axis.visibleRange; if (!elementExist && annotation.axisValue >= range.min && annotation.axisValue <= range.max) { element.appendChild(getElement(this.element.id + '_Annotation_' + annotationIndex)); } } else if (!elementExist) { element.appendChild(getElement(this.element.id + '_Annotation_' + annotationIndex)); } } } /** * To provide the array of modules needed for control rendering * * @return {ModuleDeclaration[]} * @private */ public requiredModules(): ModuleDeclaration[] { const modules: ModuleDeclaration[] = []; let annotationEnable: boolean = false; const tooltipEnable: boolean = false; this.annotations.map((annotation: Annotation, index: number) => { annotationEnable = annotation.content != null; }); if (annotationEnable) { modules.push({ member: 'Annotations', args: [this, Annotations] }); } if (this.tooltip.enable) { modules.push({ member: 'Tooltip', args: [this, GaugeTooltip] }); } if (this.allowPrint) { modules.push({ member: 'Print', args: [this] }); } if (this.allowImageExport) { modules.push({ member: 'ImageExport', args: [this] }); } if (this.allowPdfExport) { modules.push({ member: 'PdfExport', args: [this] }); } modules.push({ member: 'Gradient', args: [this, Gradient] }); return modules; } /** * Get the properties to be maintained in the persisted state. * * @private */ public getPersistData(): string { const keyEntity: string[] = ['loaded']; return this.addOnPersist(keyEntity); } /** * Get component name */ public getModuleName(): string { return 'lineargauge'; } /** * Called internally if any of the property value changed. * * @private */ public onPropertyChanged(newProp: LinearGaugeModel, oldProp: LinearGaugeModel): void { let renderer: boolean = false; let refreshBounds: boolean = false; for (const prop of Object.keys(newProp)) { switch (prop) { case 'height': case 'width': case 'margin': this.createSvg(); refreshBounds = true; break; case 'title': refreshBounds = (newProp.title === '' || oldProp.title === ''); renderer = !(newProp.title === '' || oldProp.title === ''); break; case 'titleStyle': if (newProp.titleStyle && newProp.titleStyle.size) { refreshBounds = true; } else { renderer = true; } break; case 'border': renderer = true; break; case 'background': renderer = true; break; case 'container': case 'axes': case 'orientation': refreshBounds = true; break; } } if (!refreshBounds && renderer) { this.removeSvg(); this.renderGaugeElements(); this.renderAxisElements(); } if (refreshBounds) { this.createSvg(); this.renderGaugeElements(); this.calculateBounds(); this.renderAxisElements(); } } }
the_stack
import { NodeContext, PrebootAppData, PrebootData, PrebootEvent, PrebootWindow, ServerClientRoot, } from '../common/preboot.interfaces'; import {getNodeKeyForPreboot} from '../common/get-node-key'; export function _window(): PrebootWindow { return { prebootData: (window as any)['prebootData'], getComputedStyle: window.getComputedStyle, document: document }; } export class EventReplayer { clientNodeCache: { [key: string]: Element } = {}; replayStarted = false; win: PrebootWindow; /** * Window setting and getter to facilitate testing of window * in non-browser environments */ setWindow(win: PrebootWindow) { this.win = win; } /** * Window setting and getter to facilitate testing of window * in non-browser environments */ getWindow() { if (!this.win) { this.win = _window(); } return this.win; } /** * Replay all events for all apps. this can only be run once. * if called multiple times, will only do something once */ replayAll() { if (this.replayStarted) { return; } else { this.replayStarted = true; } // loop through each of the preboot apps const prebootData = this.getWindow().prebootData || {}; const apps = prebootData.apps || []; apps.forEach(appData => this.replayForApp(appData)); // once all events have been replayed and buffers switched, then we cleanup preboot this.cleanup(prebootData); } /** * Replay all events for one app (most of the time there is just one app) * @param appData */ replayForApp(appData: PrebootAppData) { appData = <PrebootAppData>(appData || {}); // try catch around events b/c even if error occurs, we still move forward try { const events = appData.events || []; // replay all the events from the server view onto the client view events.forEach(event => this.replayEvent(appData, event)); } catch (ex) { console.error(ex); } // if we are buffering, switch the buffers this.switchBuffer(appData); } /** * Replay one particular event * @param appData * @param prebootEvent */ replayEvent(appData: PrebootAppData, prebootEvent: PrebootEvent) { appData = <PrebootAppData>(appData || {}); prebootEvent = <PrebootEvent>(prebootEvent || {}); const event = prebootEvent.event as Event; const serverNode = prebootEvent.node || {}; const nodeKey = prebootEvent.nodeKey; const clientNode = this.findClientNode({ root: appData.root, node: serverNode, nodeKey: nodeKey }); // if client node can't be found, log a warning if (!clientNode) { console.warn( `Trying to dispatch event ${event.type} to node ${nodeKey} but could not find client node. Server node is: ${serverNode}` ); return; } // now dispatch events and whatnot to the client node (clientNode as HTMLInputElement).checked = serverNode.checked; (clientNode as HTMLOptionElement).selected = serverNode.selected; (clientNode as HTMLOptionElement).value = serverNode.value; clientNode.dispatchEvent(event); } /** * Switch the buffer for one particular app (i.e. display the client * view and destroy the server view) * @param appData */ switchBuffer(appData: PrebootAppData) { appData = <PrebootAppData>(appData || {}); const root = <ServerClientRoot>(appData.root || {}); const serverView = root.serverNode; const clientView = root.clientNode; // if no client view or the server view is the body or client // and server view are the same, then don't do anything and return if (!clientView || !serverView || serverView === clientView || serverView.nodeName === 'BODY') { return; } // do a try-catch just in case something messed up try { // get the server view display mode const gcs = this.getWindow().getComputedStyle; const display = gcs(serverView).getPropertyValue('display') || 'block'; // first remove the server view serverView.remove ? serverView.remove() : (serverView.style.display = 'none'); // now add the client view clientView.style.display = display; } catch (ex) { console.error(ex); } } /** * Finally, set focus, remove all the event listeners and remove * any freeze screen that may be there * @param prebootData */ cleanup(prebootData: PrebootData) { prebootData = prebootData || {}; const listeners = prebootData.listeners || []; // set focus on the active node AFTER a small delay to ensure buffer // switched const activeNode = prebootData.activeNode; if (activeNode != null) { setTimeout(() => this.setFocus(activeNode), 1); } // remove all event listeners for (const listener of listeners) { listener.node.removeEventListener(listener.eventName, listener.handler); } // remove the freeze overlay if it exists const doc = this.getWindow().document; const prebootOverlay = doc.getElementById('prebootOverlay'); if (prebootOverlay) { prebootOverlay.remove ? prebootOverlay.remove() : prebootOverlay.parentNode !== null ? prebootOverlay.parentNode.removeChild(prebootOverlay) : prebootOverlay.style.display = 'none'; } // clear out the data stored for each app prebootData.apps = []; this.clientNodeCache = {}; // send event to document that signals preboot complete // constructor is not supported by older browsers ( i.e. IE9-11 ) // in these browsers, the type of CustomEvent will be "object" if (typeof CustomEvent === 'function') { const completeEvent = new CustomEvent('PrebootComplete'); doc.dispatchEvent(completeEvent); } else { console.warn(`Could not dispatch PrebootComplete event. You can fix this by including a polyfill for CustomEvent.`); } } setFocus(activeNode: NodeContext) { // only do something if there is an active node if (!activeNode || !activeNode.node || !activeNode.nodeKey) { return; } // find the client node in the new client view const clientNode = this.findClientNode(activeNode); if (clientNode) { // set focus on the client node clientNode.focus(); // set selection if a modern browser (i.e. IE9+, etc.) const selection = activeNode.selection; if ((clientNode as HTMLInputElement).setSelectionRange && selection) { try { (clientNode as HTMLInputElement) .setSelectionRange(selection.start, selection.end, selection.direction); } catch (ex) {} } } } /** * Given a node from the server rendered view, find the equivalent * node in the client rendered view. We do this by the following approach: * 1. take the name of the server node tag (ex. div or h1 or input) * 2. add either id (ex. div#myid) or class names (ex. div.class1.class2) * 3. use that value as a selector to get all the matching client nodes * 4. loop through all client nodes found and for each generate a key value * 5. compare the client key to the server key; once there is a match, * we have our client node * * NOTE: this only works when the client view is almost exactly the same as * the server view. we will need an improvement here in the future to account * for situations where the client view is different in structure from the * server view */ findClientNode(serverNodeContext: NodeContext): HTMLElement | null { serverNodeContext = <NodeContext>(serverNodeContext || {}); const serverNode = serverNodeContext.node; const root = serverNodeContext.root; // if no server or client root, don't do anything if (!root || !root.serverNode || !root.clientNode) { return null; } // we use the string of the node to compare to the client node & as key in // cache const serverNodeKey = serverNodeContext.nodeKey || getNodeKeyForPreboot(serverNodeContext); // if client node already in cache, return it if (this.clientNodeCache[serverNodeKey]) { return this.clientNodeCache[serverNodeKey] as HTMLElement; } // get the selector for client nodes const className = (serverNode.className || '').replace('ng-binding', '').trim(); let selector = serverNode.tagName; if (serverNode.id) { selector += `#${serverNode.id}`; } else if (className) { selector += `.${className.replace(/ /g, '.')}`; } // select all possible client nodes and look through them to try and find a // match const rootClientNode = root.clientNode; let clientNodes = rootClientNode.querySelectorAll(selector); // if nothing found, then just try the tag name as a final option if (!clientNodes.length) { console.log(`nothing found for ${selector} so using ${serverNode.tagName}`); clientNodes = rootClientNode.querySelectorAll(serverNode.tagName); } const length = clientNodes.length; for (let i = 0; i < length; i++) { const clientNode = clientNodes.item(i); // get the key for the client node const clientNodeKey = getNodeKeyForPreboot({ root: root, node: clientNode }); // if the client node key is exact match for the server node key, then we // found the client node if (clientNodeKey === serverNodeKey) { this.clientNodeCache[serverNodeKey] = clientNode; return clientNode as HTMLElement; } } // if we get here and there is one clientNode, use it as a fallback if (clientNodes.length === 1) { this.clientNodeCache[serverNodeKey] = clientNodes[0]; return clientNodes[0] as HTMLElement; } // if we get here it means we couldn't find the client node so give the user // a warning console.warn( `No matching client node found for ${serverNodeKey}. You can fix this by assigning this element a unique id attribute.` ); return null; } }
the_stack
import { RegistryEntry } from '../../src/registries/RegistryEntry'; import * as path from 'path'; import * as fs from 'fs-extra'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as chaiAsPromised from 'chai-as-promised'; import { FileRegistry } from '../../src/registries/FileRegistry'; chai.should(); chai.use(chaiAsPromised); // tslint:disable no-unused-expression describe('FileRegistry', () => { const testFabricRegistryName: string = 'test'; const testRegistriesPath: string = path.join(__dirname, 'tmp', 'registries'); // tslint:disable max-classes-per-file class TestFabricRegistryEntry extends RegistryEntry { public myValue: string; constructor(fields?: TestFabricRegistryEntry) { super(); Object.assign(this, fields); } } // tslint:disable max-classes-per-file class TestFabricRegistry extends FileRegistry<TestFabricRegistryEntry> { constructor() { super(testFabricRegistryName); } } let registry: TestFabricRegistry; let emitSpy: sinon.SinonSpy; let mySandbox: sinon.SinonSandbox; before(async () => { mySandbox = sinon.createSandbox(); registry = new TestFabricRegistry(); registry.setRegistryPath(testRegistriesPath); }); beforeEach(async () => { await registry.clear(); emitSpy = mySandbox.spy(registry, 'emit'); }); afterEach(async () => { mySandbox.restore(); }); describe('#getRegistriesPath', () => { it('should get the registries path', () => { const result: string = registry.getRegistryPath(); result.should.equal(testRegistriesPath); }); }); describe('#getAll', () => { it('should get no entries if the configuration is empty', async () => { const testEntries: TestFabricRegistryEntry[] = []; await registry.clear(); emitSpy.resetHistory(); await registry.getAll().should.eventually.deep.equal(testEntries); emitSpy.should.not.have.been.called; }); it('should get all entries if the configuration is not empty', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); const testEntries: TestFabricRegistryEntry[] = [testA, testB]; emitSpy.resetHistory(); await registry.getAll().should.eventually.deep.equal(testEntries); emitSpy.should.not.have.been.called; }); it('should get all entries if the configuration is not empty', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); const testEntries: TestFabricRegistryEntry[] = [testA, testB]; emitSpy.resetHistory(); await registry.getAll().should.eventually.deep.equal(testEntries); emitSpy.should.not.have.been.called; }); it('should ignore entries without a config file', async () => { const registryPath: string = path.join(testRegistriesPath, testFabricRegistryName, 'test'); await fs.ensureDir(registryPath); const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); const testEntries: TestFabricRegistryEntry[] = [testA, testB]; emitSpy.resetHistory(); await registry.getAll().should.eventually.deep.equal(testEntries); emitSpy.should.not.have.been.called; }); }); describe('#get', () => { it('should get an entry if the entry exists in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); const testEntries: TestFabricRegistryEntry[] = [testA, testB]; emitSpy.resetHistory(); await registry.get('foo2').should.eventually.deep.equal(testEntries[1]); emitSpy.should.not.have.been.called; }); it('should throw if an entry does not exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.get('foo0').should.eventually.be.rejectedWith(`Entry "foo0" in registry "${testFabricRegistryName}" does not exist`); emitSpy.should.not.have.been.called; }); }); describe('#exists', () => { it('should return true if the entry exists in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.exists('foo2').should.eventually.be.true; emitSpy.should.not.have.been.called; }); it('should return false if an entry does not exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.exists('foo0').should.eventually.be.false; emitSpy.should.not.have.been.called; }); }); describe('#add', () => { it('should throw if an entry does exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.add(testA).should.eventually.be.rejectedWith(`Entry "foo1" in registry "${testFabricRegistryName}" already exists`); emitSpy.should.not.have.been.called; }); it('should add an entry if the entry does not exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); await registry.getAll().should.eventually.deep.equal([testA, testB]); const newEntry: TestFabricRegistryEntry = { name: 'foo0', myValue: 'value0' }; await registry.add(newEntry); await registry.getAll().should.eventually.deep.equal([newEntry, testA, testB]); emitSpy.should.have.been.calledWith(FileRegistry.EVENT_NAME, testFabricRegistryName); }); }); describe('#update', () => { it('should throw if an entry does not exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); const newEntry: TestFabricRegistryEntry = { name: 'foo0', myValue: 'value0' }; await registry.update(newEntry).should.be.rejectedWith(`Entry "foo0" in registry "${testFabricRegistryName}" does not exist`); emitSpy.should.not.have.been.called; }); it('should update an entry if the entry exists in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); const newEntry: TestFabricRegistryEntry = { name: 'foo2', myValue: 'value2+1' }; await registry.update(newEntry); await registry.get('foo2').should.eventually.deep.equal(newEntry); emitSpy.should.have.been.calledWith(FileRegistry.EVENT_NAME, testFabricRegistryName); }); }); describe('#delete', () => { it('should throw if an entry does not exist in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.delete('foo0').should.be.rejectedWith(`Entry "foo0" in registry "${testFabricRegistryName}" does not exist`); emitSpy.should.not.have.been.called; }); it('should delete an entry if the entry exists in the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.delete('foo2'); await registry.getAll().should.eventually.deep.equal([testA]); emitSpy.should.have.been.calledWith(FileRegistry.EVENT_NAME, testFabricRegistryName); }); it('should not throw if ignoreNotExists is set', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.delete('foo0', true).should.not.be.rejected; emitSpy.should.not.have.been.called; }); }); describe('#clear', () => { it('should delete all entries from the configuration', async () => { const testA: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo1', myValue: 'value1' }); const testB: TestFabricRegistryEntry = new TestFabricRegistryEntry({ name: 'foo2', myValue: 'value2' }); await registry.add(testA); await registry.add(testB); emitSpy.resetHistory(); await registry.clear(); await registry.getAll().should.eventually.deep.equal([]); emitSpy.should.have.been.calledWith(FileRegistry.EVENT_NAME, testFabricRegistryName); }); }); });
the_stack
import { FEED_PACKAGE, NPM_PACKAGE } from "@igniteui/angular-templates"; import { GoogleAnalytics, GoogleAnalyticsParameters, ProjectConfig } from "@igniteui/cli-core"; import * as fs from "fs-extra"; import { EOL } from "os"; import { parse } from "path"; import * as cli from "../../packages/cli/lib/cli"; import { deleteAll, resetSpy } from "../helpers/utils"; describe("Add command", () => { let testFolder = parse(__filename).name; // tslint:disable:no-console beforeEach(() => { spyOn(console, "log"); spyOn(console, "error"); spyOn(GoogleAnalytics, "post"); // test folder, w/ existing check: while (fs.existsSync(`./output/${testFolder}`)) { testFolder += 1; } fs.mkdirSync(`./output/${testFolder}`); process.chdir(`./output/${testFolder}`); }); afterEach(() => { // clean test folder: process.chdir("../../"); fs.rmdirSync(`./output/${testFolder}`); }); it("Should not work without a project", async done => { await cli.run(["add", "grid", "name"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/Add command is supported only on existing project created with igniteui-cli\s*/) ); expect(console.log).toHaveBeenCalledTimes(0); let expectedPrams: GoogleAnalyticsParameters = { t: "screenview", cd: "Add" }; expect(GoogleAnalytics.post).toHaveBeenCalledWith(expectedPrams); expectedPrams = { t: "screenview", cd: "error: Add command is supported only on existing project created with igniteui-cli" }; expect(GoogleAnalytics.post).toHaveBeenCalledWith(expectedPrams); expect(GoogleAnalytics.post).toHaveBeenCalledTimes(2); resetSpy(console.error); await cli.run(["add"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/Add command is supported only on existing project created with igniteui-cli\s*/) ); expect(console.log).toHaveBeenCalledTimes(0); done(); }); it("Should not work quickstart project", async done => { fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { isShowcase: true } })); await cli.run(["add", "grid", "name"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/Showcases and quickstart projects don't support the add command\s*/) ); expect(console.log).toHaveBeenCalledTimes(0); fs.unlinkSync(ProjectConfig.configFile); done(); }); it("Should not work with wrong framework", async done => { fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "angular2" } })); await cli.run(["add", "grid", "name"]); expect(console.error).toHaveBeenCalledWith(jasmine.stringMatching(/Framework not supported\s*/)); expect(console.log).toHaveBeenCalledTimes(0); fs.unlinkSync(ProjectConfig.configFile); done(); }); it("Should not work with wrong template", async done => { fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "jquery" } })); await cli.run(["add", "wrong", "name"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/Template doesn't exist in the current library\s*/) ); expect(console.log).toHaveBeenCalledTimes(0); fs.unlinkSync(ProjectConfig.configFile); done(); }); it("Should correctly add jQuery template", async done => { // TODO: Mock out template manager and project register spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "jquery", projectType: "js", components: [], igniteuiSource: "", themePath: "" } })); fs.writeFileSync("ignite-cli-views.js", "[];"); await cli.run(["add", "grid", "Test view"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'Test view' added\s*/)); expect(fs.existsSync("./test-view")).toBeTruthy(); expect(fs.existsSync("./test-view/index.html")).toBeTruthy(); fs.unlinkSync("./test-view/index.html"); fs.unlinkSync("./test-view/style.css"); fs.rmdirSync("./test-view"); fs.unlinkSync("ignite-cli-views.js"); fs.unlinkSync(ProjectConfig.configFile); done(); }); it("Should not duplicate add jq Grid template", async done => { spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "jquery", projectType: "js", components: [], igniteuiSource: "", themePath: "" } })); fs.writeFileSync("ignite-cli-views.js", "[];"); await cli.run(["add", "grid", "Test view"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'Test view' added\s*/)); expect(fs.existsSync("./test-view")).toBeTruthy(); expect(fs.existsSync("./test-view/index.html")).toBeTruthy(); fs.writeFileSync("./test-view/index.html", "test"); await cli.run(["add", "grid", "Test view"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/test-view[\\\/]index.html already exists!*/) ); expect(fs.readFileSync("./test-view/index.html").toString()).toEqual("test", "Shouldn't overwrite file contents"); // dash resetSpy(console.error); await cli.run(["add", "grid", "test-View"]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/test-view[\\\/]index.html already exists!*/) ); expect(fs.readFileSync("./test-view/index.html").toString()).toEqual("test", "Shouldn't overwrite file contents"); // trim resetSpy(console.error); await cli.run(["add", "grid", " Test-view \t "]); expect(console.error).toHaveBeenCalledWith( jasmine.stringMatching(/test-view[\\\/]index.html already exists!*/) ); expect(fs.readFileSync("./test-view/index.html").toString()).toEqual("test", "Shouldn't overwrite file contents"); fs.unlinkSync("./test-view/index.html"); fs.unlinkSync("./test-view/style.css"); fs.rmdirSync("./test-view"); fs.unlinkSync("ignite-cli-views.js"); fs.unlinkSync(ProjectConfig.configFile); done(); }); it("Should correctly add Angular template", async done => { spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "angular", projectType: "ig-ts", components: [] } })); fs.mkdirSync(`./src`); fs.mkdirSync(`./src/app`); fs.writeFileSync("src/app/app-routing.module.ts", "const routes: Routes = [];"); fs.writeFileSync("src/app/app.module.ts", `@NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule { }`); await cli.run(["add", "grid", "Test view"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'Test view' added\s*/)); expect(fs.existsSync("./src/app/components/test-view")).toBeTruthy(); const componentPath = "./src/app/components/test-view/test-view.component.ts"; expect(fs.existsSync(componentPath)).toBeTruthy(); // file contents: expect(fs.readFileSync(componentPath, "utf-8")).toContain("export class TestViewComponent"); expect(fs.readFileSync("src/app/app-routing.module.ts", "utf-8").replace(/\s/g, "")).toBe( `import { TestViewComponent } from "./components/test-view/test-view.component"; const routes: Routes = [{ path: "test-view", component: TestViewComponent, data: { text: "Test view" } }]; `.replace(/\s/g, "") ); expect(fs.readFileSync("src/app/app.module.ts", "utf-8").replace(/\s/g, "")).toBe( `import { TestViewComponent } from "./components/test-view/test-view.component"; @NgModule({ declarations: [ AppComponent, HomeComponent, TestViewComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule { } `.replace(/\s/g, "") ); fs.unlinkSync("./src/app/components/test-view/test-view.component.ts"); fs.removeSync("./src"); fs.unlinkSync(ProjectConfig.configFile); let expectedPrams: GoogleAnalyticsParameters = { t: "screenview", cd: "Add" }; expect(GoogleAnalytics.post).toHaveBeenCalledWith(expectedPrams); expectedPrams = { t: "event", ec: "$ig add", ea: "template id: grid; file name: Test view", cd1: "angular", cd2: "ig-ts", cd5: "Data Grids", cd7: "grid", cd8: "Grid", cd11: false, cd14: undefined }; expect(GoogleAnalytics.post).toHaveBeenCalledWith(expectedPrams); expect(GoogleAnalytics.post).toHaveBeenCalledTimes(2); done(); }); for (const igxPackage of [NPM_PACKAGE, FEED_PACKAGE]) { it(`Should correctly add Ignite UI for Angular template - ${igxPackage}`, async done => { spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync("package.json", JSON.stringify({ dependencies: { [igxPackage]: "9.0.0" } })); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "angular", projectType: "igx-ts", components: [] } })); fs.writeFileSync("tslint.json", JSON.stringify({ rules: { "indent": [true, "spaces", 2], "prefer-const": true, "quotemark": [true, "single"] } })); fs.mkdirSync(`./src`); fs.mkdirSync(`./src/app`); fs.writeFileSync("src/app/app-routing.module.ts", "const routes: Routes = [];"); fs.writeFileSync("src/app/app.module.ts", `@NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule { }`); await cli.run(["add", "grid", "Test view"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'Test view' added\s*/)); expect(fs.existsSync("./src/app/test-view")).toBeTruthy(); const componentPath = "./src/app/test-view/test-view.component.ts"; expect(fs.existsSync(componentPath)).toBeTruthy(); // file contents: expect(fs.readFileSync(componentPath, "utf-8")).toContain("export class TestViewComponent"); expect(fs.readFileSync("src/app/app-routing.module.ts", "utf-8")).toBe( `import { TestViewComponent } from './test-view/test-view.component';` + EOL + `const routes: Routes = [{ path: 'test-view', component: TestViewComponent, data: { text: 'Test view' } }];` + EOL ); const expectedModuleSource = `import { TestViewComponent } from './test-view/test-view.component'; import { IgxGridModule } from '${igxPackage}'; @NgModule({ declarations: [ AppComponent, HomeComponent, TestViewComponent ], imports: [ BrowserModule, IgxGridModule ], bootstrap: [AppComponent] }) export class AppModule { } `; expect(fs.readFileSync("src/app/app.module.ts", "utf-8").replace(/\r\n/g, "\n")) .toBe(expectedModuleSource.replace(/\r\n/g, "\n")); fs.unlinkSync("./src/app/test-view/test-view.component.ts"); fs.removeSync("./src"); fs.unlinkSync(ProjectConfig.configFile); fs.unlinkSync("tslint.json"); fs.unlinkSync("package.json"); done(); }); } it("Should correctly add Ignite UI for Angular template passing folders path and spaces/tabs in name arg" , async done => { spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "angular", projectType: "igx-ts", components: [] } })); fs.writeFileSync("tslint.json", JSON.stringify({ rules: { "indent": [true, "spaces", 2], "prefer-const": true, "quotemark": [true, "single"] } })); fs.mkdirSync(`./src`); fs.mkdirSync(`./src/app`); fs.writeFileSync("src/app/app-routing.module.ts", "const routes: Routes = [];"); fs.writeFileSync("src/app/app.module.ts", `@NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule { }`); await cli.run(["add", "grid", "folder/test nested folders/ \t Test Nested Folders \t"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'Test Nested Folders' added\s*/)); const componentFolder = "folder/test-nested-folders/test-nested-folders"; expect(fs.existsSync(`./src/app/${componentFolder}`)).toBeTruthy(); const componentPath = `./src/app/${componentFolder}/test-nested-folders.component.ts`; expect(fs.existsSync(componentPath)).toBeTruthy(); // file contents: expect(fs.readFileSync(componentPath, "utf-8")).toContain("export class TestNestedFoldersComponent"); expect(fs.readFileSync("src/app/app-routing.module.ts", "utf-8")).toBe( `import { TestNestedFoldersComponent } from './${componentFolder}/test-nested-folders.component';` + EOL + // tslint:disable-next-line:max-line-length `const routes: Routes = [{ path: 'test-nested-folders', component: TestNestedFoldersComponent, data: { text: 'Test Nested Folders' } }];` + EOL ); expect(fs.readFileSync("src/app/app.module.ts", "utf-8")).toBe( `import { TestNestedFoldersComponent } from './${componentFolder}/test-nested-folders.component';` + EOL + `import { IgxGridModule } from 'igniteui-angular';` + EOL + `@NgModule({` + EOL + ` declarations: [` + EOL + ` AppComponent,` + EOL + ` HomeComponent,` + EOL + ` TestNestedFoldersComponent` + EOL + ` ],` + EOL + ` imports: [` + EOL + ` BrowserModule,` + EOL + ` IgxGridModule` + EOL + ` ],` + EOL + ` bootstrap: [AppComponent]` + EOL + `})` + EOL + `export class AppModule {` + EOL + `}` + EOL ); deleteAll("./src"); fs.rmdirSync("./src"); fs.unlinkSync(ProjectConfig.configFile); fs.unlinkSync("tslint.json"); done(); }); it("Should correctly add React template", async done => { // TODO: Mock out template manager and project register spyOn(ProjectConfig, "globalConfig").and.returnValue({}); fs.writeFileSync(ProjectConfig.configFile, JSON.stringify({ project: { framework: "react", projectType: "es6", components: [] } })); fs.mkdirSync(`./src`); fs.writeFileSync("src/routes.json", "[]"); await cli.run(["add", "grid", "My grid"]); expect(console.error).toHaveBeenCalledTimes(0); expect(console.log).toHaveBeenCalledWith(jasmine.stringMatching(/View 'My grid' added\s*/)); expect(fs.existsSync("./src/components/my-grid")).toBeTruthy(); expect(fs.existsSync("./src/components/my-grid/index.js")).toBeTruthy(); fs.unlinkSync("./src/components/my-grid/index.js"); fs.removeSync("./src"); fs.unlinkSync(ProjectConfig.configFile); done(); }); });
the_stack
import {getTestEnv} from './prepare'; const env = getTestEnv(); const x509 = env.library; const envName = env.envName; import sample from './sample_crt'; import rsa from 'js-crypto-rsa'; import {Key} from 'js-crypto-key-utils'; import {HashTypes, SignatureType} from '../src/typedef'; const hashes: Array<HashTypes> = ['SHA-256', 'SHA-384', 'SHA-512'];//, 'SHA-1']; const pkcs1s: Array<SignatureType> = [ 'sha256WithRSAEncryption', 'sha384WithRSAEncryption', 'sha512WithRSAEncryption']; // RSASSA-PKCS1-v1_5 const constantSaltLen = 32; describe(`${envName}: RSA: Generated JWK public key should be successfully converted to X509 PEM certificate and vice versa`, () => { beforeAll(async () => { }); it('Transform JWKs to X509 RSASSA-PKCS1-v1_5 PEM as self signed cert and verify generated one', async () => { const name = { countryName: 'JP', stateOrProvinceName: 'Tokyo', localityName: 'Chiyoda', organizationName: 'example', organizationalUnitName: 'Research', commonName: 'example.com' }; const results = await Promise.all(pkcs1s.map( async (signatureAlgorithm) => { const publicObj = new Key('pem', sample.rsa.publicKey); const privateObj = new Key('pem', sample.rsa.privateKey); const crt = await x509.fromJwk( <JsonWebKey>await publicObj.export('jwk'), <JsonWebKey>await privateObj.export('jwk'), 'pem', { signature: signatureAlgorithm, days: 365, issuer: name, subject: name } ); console.log(x509.info(crt,'pem')); const parsed = await x509.parse(crt, 'pem'); // console.log(parsed.signatureAlgorithm); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, <JsonWebKey>await publicObj.export('jwk'), parsed.signatureAlgorithm.parameters.hash, {name: 'RSASSA-PKCS1-v1_5'} ); return re; })); console.log(results); expect(results.every( (elem) => elem === true)).toBeTruthy(); }); it('Transform JWKs to X509 RSA-PSS Empty Parameter PEM as self signed cert and verify generated one', async () => { const name = { countryName: 'JP', stateOrProvinceName: 'Tokyo', localityName: 'Chiyoda', organizationName: 'example', organizationalUnitName: 'Research', commonName: 'example.com' }; const publicObj = new Key('pem', sample.rsa.publicKey); const privateObj = new Key('pem', sample.rsa.privateKey); const crt = await x509.fromJwk( <JsonWebKey>await publicObj.export('jwk'), <JsonWebKey>await privateObj.export('jwk'), 'pem', { signature: 'rsassaPss', days: 365, issuer: name, subject: name } ); console.log(x509.info(crt,'pem')); const parsed = await x509.parse(crt, 'pem'); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, <JsonWebKey>await publicObj.export('jwk'), parsed.signatureAlgorithm.parameters.hash, {name: 'RSA-PSS', saltLength: parsed.signatureAlgorithm.parameters.saltLength} ); console.log(re); expect(re).toBeTruthy(); }); it('Transform JWKs to X509 RSA-PSS Explicit Parameter PEM as self signed cert and verify generated one', async () => { const name = { countryName: 'JP', stateOrProvinceName: 'Tokyo', localityName: 'Chiyoda', organizationName: 'example', organizationalUnitName: 'Research', commonName: 'example.com' }; const publicObj = new Key('pem', sample.rsa.publicKey); const privateObj = new Key('pem', sample.rsa.privateKey); const results = await Promise.all(hashes.map( async (hash) => { const crt = await x509.fromJwk( <JsonWebKey>await publicObj.export('jwk'), <JsonWebKey>await privateObj.export('jwk'), 'pem', { signature: 'rsassaPss', days: 365, issuer: name, subject: name, pssParams: {saltLength: constantSaltLen, hash} } ); console.log(x509.info(crt,'pem')); const parsed = x509.parse(crt, 'pem'); // console.log(parsed.signatureAlgorithm); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, <JsonWebKey>await publicObj.export('jwk'), parsed.signatureAlgorithm.parameters.hash, {name: 'RSA-PSS', saltLength: parsed.signatureAlgorithm.parameters.saltLength} ); return re; })); console.log(results); expect(results.every( (elem) => elem === true)).toBeTruthy(); }); it('Transform X509 Self Signed RSASSA-PKCS1-v1_5 PEM to JWK, and verify it', async () => { const jwkey = await x509.toJwk(sample.rsa.certificatePKCS1v1_5, 'pem'); const parsed = x509.parse(sample.rsa.certificatePKCS1v1_5, 'pem'); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, jwkey, parsed.signatureAlgorithm.parameters.hash, {name: 'RSASSA-PKCS1-v1_5'} ); // = await rsa.verify(parsed.tbsCertificate, parsed.signatureValue, jwkey, parsed.hash, 'der'); console.log(re); expect(re).toBeTruthy(); }); it('Transform X509 Self Signed RSA-PSS Explicit Parameter PEM to JWK, and verify it', async () => { const samplePss = '-----BEGIN CERTIFICATE-----\n' + 'MIIFazCCBCKgAwIBAgIJAKmJV6cI/tYpMD4GCSqGSIb3DQEBCjAxoAswCQYFKw4D\n' + 'AhoFAKEYMBYGCSqGSIb3DQEBCDAJBgUrDgMCGgUAogMCARSjAwIBATCBszELMAkG\n' + 'A1UEBhMCREUxDzANBgNVBAgTBkhlc3NlbjESMBAGA1UEBxMJRnJhbmtmdXJ0MR4w\n' + 'HAYDVQQKExVQU1MgdGVzdCBjZXJ0aWZpY2F0ZXMxOTA3BgNVBAsTMGNyZWF0ZWQg\n' + 'YnkgTWFydGluIEthaXNlciAoaHR0cDovL3d3dy5rYWlzZXIuY3gvKTEkMCIGA1UE\n' + 'AxMbUFNTIHRlc3RSb290IENBIENlcnRpZmljYXRlMB4XDTEwMDcxMzE5NTc1NVoX\n' + 'DTE2MDEwMzE5NTc1NVowgbMxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZIZXNzZW4x\n' + 'EjAQBgNVBAcTCUZyYW5rZnVydDEeMBwGA1UEChMVUFNTIHRlc3QgY2VydGlmaWNh\n' + 'dGVzMTkwNwYDVQQLEzBjcmVhdGVkIGJ5IE1hcnRpbiBLYWlzZXIgKGh0dHA6Ly93\n' + 'd3cua2Fpc2VyLmN4LykxJDAiBgNVBAMTG1BTUyB0ZXN0Um9vdCBDQSBDZXJ0aWZp\n' + 'Y2F0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMZnLiVdh/4aR2Gj\n' + 'FKBiDmuNe8o6NJSgNRMXv+zweb1CQRUQ4HzdiZDRBTxAGM+83/ofeD3ALUyDGniX\n' + 'fbjxv05QyPGnJDjJYpdQ3ilM4MXoEYz7ZfB4/AVh1zvqELFR3a2TZ78oQGYJBeF3\n' + 'vAmVuDwCrZ8J7xddABt7ceqDtzhhNcvOWDZxXtzK5yDtb4N/RMJZtbK6ZNsLV/+J\n' + 'OMHT+22xycE6tE2gMCqUUC2b2MpnW71GqtkKxaA36VXl/c4Z0IhNE2Zx3qy5NVsU\n' + 'Z+NYw6JrWtEw+kf2j0bKj5w0LMlERKbNib4kofcMJ8qPEIvk1u6T30vKUb7HQdU7\n' + '2OuTWQ8CAwEAAaOCARwwggEYMB0GA1UdDgQWBBTfH+IBoj70+Wn4OseW1pkNL7bO\n' + 'MzCB6AYDVR0jBIHgMIHdgBTfH+IBoj70+Wn4OseW1pkNL7bOM6GBuaSBtjCBszEL\n' + 'MAkGA1UEBhMCREUxDzANBgNVBAgTBkhlc3NlbjESMBAGA1UEBxMJRnJhbmtmdXJ0\n' + 'MR4wHAYDVQQKExVQU1MgdGVzdCBjZXJ0aWZpY2F0ZXMxOTA3BgNVBAsTMGNyZWF0\n' + 'ZWQgYnkgTWFydGluIEthaXNlciAoaHR0cDovL3d3dy5rYWlzZXIuY3gvKTEkMCIG\n' + 'A1UEAxMbUFNTIHRlc3RSb290IENBIENlcnRpZmljYXRlggkAqYlXpwj+1ikwDAYD\n' + 'VR0TBAUwAwEB/zA+BgkqhkiG9w0BAQowMaALMAkGBSsOAwIaBQChGDAWBgkqhkiG\n' + '9w0BAQgwCQYFKw4DAhoFAKIDAgEUowMCAQEDggEBAJ8GcFT/Jdhz65JK0c9EFdAq\n' + '8FKa9VWX7QDQlIuu0UbZaHYaFmY1NbXcxlvTOD1ArByCHpFQ8+wrXgLrxedlm/fI\n' + '9WkvFsyvC1kSeV88C90E3mh+w9i2Qsz0Gjj2RjD98cPsqqQO7q/7uvKNcHMN5nKi\n' + 'VuIPMr5fisx0C/IBQAunBfzBfdGmjoNaahDBYCKiyAaU7A+dYorRbMJF7SxBhTr1\n' + 'WI/N3LlBKLF5mvtDYg7sXx6ULR/xAKKkVeUTIgGMYq/s46ZMP11QrfRHx4zNAwP9\n' + 'aARZeUz1X0/LM6LgaQvVIhZqbyB637eZhusOP3226TDn7hGx/UdS0UxSwfjrzS8=\n' + '-----END CERTIFICATE-----'; const jwkey = await x509.toJwk(samplePss, 'pem'); console.log(jwkey); const parsed = x509.parse(samplePss, 'pem'); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, jwkey, parsed.signatureAlgorithm.parameters.hash, {name: 'RSA-PSS', saltLength: parsed.signatureAlgorithm.parameters.saltLength} ); // = await rsa.verify(parsed.tbsCertificate, parsed.signatureValue, jwkey, parsed.hash, 'der'); console.log(re); expect(re).toBeTruthy(); }); it('Transform X509 Self Signed RSA-PSS Empty Parameter PEM to JWK, and verify it', async () => { const samplePss = '-----BEGIN CERTIFICATE-----\n' + 'MIIFCTCCA/GgAwIBAgIJALCOVlO1QTu1MA0GCSqGSIb3DQEBCjAAMIGzMQswCQYD\n' + 'VQQGEwJERTEPMA0GA1UECBMGSGVzc2VuMRIwEAYDVQQHEwlGcmFua2Z1cnQxHjAc\n' + 'BgNVBAoTFVBTUyB0ZXN0IGNlcnRpZmljYXRlczE5MDcGA1UECxMwY3JlYXRlZCBi\n' + 'eSBNYXJ0aW4gS2Fpc2VyIChodHRwOi8vd3d3LmthaXNlci5jeC8pMSQwIgYDVQQD\n' + 'ExtQU1MgdGVzdFJvb3QgQ0EgQ2VydGlmaWNhdGUwHhcNMTAwNzEzMTk1NjAzWhcN\n' + 'MTYwMTAzMTk1NjAzWjCBszELMAkGA1UEBhMCREUxDzANBgNVBAgTBkhlc3NlbjES\n' + 'MBAGA1UEBxMJRnJhbmtmdXJ0MR4wHAYDVQQKExVQU1MgdGVzdCBjZXJ0aWZpY2F0\n' + 'ZXMxOTA3BgNVBAsTMGNyZWF0ZWQgYnkgTWFydGluIEthaXNlciAoaHR0cDovL3d3\n' + 'dy5rYWlzZXIuY3gvKTEkMCIGA1UEAxMbUFNTIHRlc3RSb290IENBIENlcnRpZmlj\n' + 'YXRlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2haEKyn8mtVODAPA\n' + 'EMV9VlNm+HPBh+Mve5nPoU4PZ198E2JQ1llvXbDWmhuKzn/ZyB2janx/imvylkOq\n' + 'Jmkdqka+VC+69/pDmhHKp2qHL6S/alPG6E2kQhy4FVIEU2Qme6niMZY4005237Pi\n' + 'fWc1MBEU2c6jdkUIbw5SrWub5dbMIi71lUPHzaLqGovkLaWg2+BnPOSdg13t3jLt\n' + 'N6Dm9VMpDE0sOu/t582bc2MfCmO/vIsSpu2/iA+gB4vecDBJGyOISYKKvjnc4N2s\n' + 'Obok9ZgJKeTM40hGXEGzE+cTEDkkh8ydlGVRIJe3o5wjuLH3P51/EFVu0PhCSyV6\n' + 'FGIO1wIDAQABo4IBHDCCARgwHQYDVR0OBBYEFM4ICyE/5cAobWjQ7LPGLrAU/gbD\n' + 'MIHoBgNVHSMEgeAwgd2AFM4ICyE/5cAobWjQ7LPGLrAU/gbDoYG5pIG2MIGzMQsw\n' + 'CQYDVQQGEwJERTEPMA0GA1UECBMGSGVzc2VuMRIwEAYDVQQHEwlGcmFua2Z1cnQx\n' + 'HjAcBgNVBAoTFVBTUyB0ZXN0IGNlcnRpZmljYXRlczE5MDcGA1UECxMwY3JlYXRl\n' + 'ZCBieSBNYXJ0aW4gS2Fpc2VyIChodHRwOi8vd3d3LmthaXNlci5jeC8pMSQwIgYD\n' + 'VQQDExtQU1MgdGVzdFJvb3QgQ0EgQ2VydGlmaWNhdGWCCQCwjlZTtUE7tTAMBgNV\n' + 'HRMEBTADAQH/MA0GCSqGSIb3DQEBCjAAA4IBAQCBgFRdPf+k9up9PwwbHORNe8HP\n' + 'c7+yXPDK/qH74bJMQvaNOpXhvb0KWDcj5GPJ0l+eVatV1UzyDZT6exqaBTeWjgKW\n' + '1HMfF9z3Ybs1PTKt8IASFNMe4Nizx6vuAvnP/GXTz7LwOZt7QYBTaAOKUQqB/yBQ\n' + 'D9Vn+P+nqgQCBfFhVXPurUFpAt6npnKpKIG8wmMBoeeuWpzMFs0Rnf9TFJt9SkAn\n' + 'M8J806yQWShmibcQWmmveHtN8s/69FUUIu6q1h0A8qxISj87CdC4XKvLRV6DSu4C\n' + '+b/CfhHaOR8lINDcVYg4j3VZU24nmPlWcH4yXO8gbnoMOLnf36/Ezw3wnVIV\n' + '-----END CERTIFICATE-----'; const jwkey = await x509.toJwk(samplePss, 'pem'); const parsed = x509.parse(samplePss, 'pem'); const re = await rsa.verify( parsed.tbsCertificate, parsed.signatureValue, jwkey, parsed.signatureAlgorithm.parameters.hash, {name: 'RSA-PSS', saltLength: parsed.signatureAlgorithm.parameters.saltLength} ); console.log(re); expect(re).toBeTruthy(); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; export const acceptLanguage: msRest.OperationParameter = { parameterPath: "acceptLanguage", mapper: { serializedName: "accept-language", defaultValue: 'en-US', type: { name: "String" } } }; export const apiVersion: msRest.OperationQueryParameter = { parameterPath: "apiVersion", mapper: { required: true, serializedName: "api-version", type: { name: "String" } } }; export const backupId: msRest.OperationURLParameter = { parameterPath: "backupId", mapper: { required: true, serializedName: "backupId", type: { name: "String" } } }; export const baseAddress: msRest.OperationURLParameter = { parameterPath: "baseAddress", mapper: { required: true, serializedName: "baseAddress", type: { name: "String" } } }; export const billingLocation: msRest.OperationQueryParameter = { parameterPath: [ "options", "billingLocation" ], mapper: { serializedName: "billingLocation", type: { name: "String" } } }; export const deleteEmptyServerFarm: msRest.OperationQueryParameter = { parameterPath: [ "options", "deleteEmptyServerFarm" ], mapper: { serializedName: "deleteEmptyServerFarm", type: { name: "Boolean" } } }; export const deleteMetrics: msRest.OperationQueryParameter = { parameterPath: [ "options", "deleteMetrics" ], mapper: { serializedName: "deleteMetrics", type: { name: "Boolean" } } }; export const detailed: msRest.OperationQueryParameter = { parameterPath: [ "options", "detailed" ], mapper: { serializedName: "detailed", type: { name: "Boolean" } } }; export const details: msRest.OperationQueryParameter = { parameterPath: [ "options", "details" ], mapper: { serializedName: "details", type: { name: "Boolean" } } }; export const domainOwnershipIdentifierName: msRest.OperationURLParameter = { parameterPath: "domainOwnershipIdentifierName", mapper: { required: true, serializedName: "domainOwnershipIdentifierName", type: { name: "String" } } }; export const durationInSeconds: msRest.OperationQueryParameter = { parameterPath: [ "options", "durationInSeconds" ], mapper: { serializedName: "durationInSeconds", type: { name: "Number" } } }; export const entityName: msRest.OperationURLParameter = { parameterPath: "entityName", mapper: { required: true, serializedName: "entityName", type: { name: "String" } } }; export const environmentName: msRest.OperationQueryParameter = { parameterPath: "environmentName", mapper: { required: true, serializedName: "environmentName", type: { name: "String" } } }; export const expiredOnly: msRest.OperationQueryParameter = { parameterPath: [ "options", "expiredOnly" ], mapper: { serializedName: "expiredOnly", type: { name: "Boolean" } } }; export const featured: msRest.OperationQueryParameter = { parameterPath: [ "options", "featured" ], mapper: { serializedName: "featured", type: { name: "Boolean" } } }; export const filter: msRest.OperationQueryParameter = { parameterPath: [ "options", "filter" ], mapper: { serializedName: "$filter", type: { name: "String" } }, skipEncoding: true }; export const functionName: msRest.OperationURLParameter = { parameterPath: "functionName", mapper: { required: true, serializedName: "functionName", type: { name: "String" } } }; export const gatewayName: msRest.OperationURLParameter = { parameterPath: "gatewayName", mapper: { required: true, serializedName: "gatewayName", type: { name: "String" } } }; export const hostingEnvironmentName: msRest.OperationURLParameter = { parameterPath: "hostingEnvironmentName", mapper: { required: true, serializedName: "hostingEnvironmentName", type: { name: "String" } } }; export const hostName0: msRest.OperationQueryParameter = { parameterPath: [ "options", "hostName" ], mapper: { serializedName: "hostName", type: { name: "String" } } }; export const hostName1: msRest.OperationURLParameter = { parameterPath: "hostName", mapper: { required: true, serializedName: "hostName", type: { name: "String" } } }; export const id: msRest.OperationURLParameter = { parameterPath: "id", mapper: { required: true, serializedName: "id", type: { name: "String" } } }; export const includeSlots: msRest.OperationQueryParameter = { parameterPath: [ "options", "includeSlots" ], mapper: { serializedName: "includeSlots", type: { name: "Boolean" } } }; export const instanceId: msRest.OperationURLParameter = { parameterPath: "instanceId", mapper: { required: true, serializedName: "instanceId", type: { name: "String" } } }; export const linuxDynamicWorkersEnabled: msRest.OperationQueryParameter = { parameterPath: [ "options", "linuxDynamicWorkersEnabled" ], mapper: { serializedName: "linuxDynamicWorkersEnabled", type: { name: "Boolean" } } }; export const linuxWorkersEnabled: msRest.OperationQueryParameter = { parameterPath: [ "options", "linuxWorkersEnabled" ], mapper: { serializedName: "linuxWorkersEnabled", type: { name: "Boolean" } } }; export const maxFrameLength: msRest.OperationQueryParameter = { parameterPath: [ "options", "maxFrameLength" ], mapper: { serializedName: "maxFrameLength", type: { name: "Number" } } }; export const name: msRest.OperationURLParameter = { parameterPath: "name", mapper: { required: true, serializedName: "name", type: { name: "String" } } }; export const namespaceName: msRest.OperationURLParameter = { parameterPath: "namespaceName", mapper: { required: true, serializedName: "namespaceName", type: { name: "String" } } }; export const nextPageLink: msRest.OperationURLParameter = { parameterPath: "nextPageLink", mapper: { required: true, serializedName: "nextLink", type: { name: "String" } }, skipEncoding: true }; export const operationId: msRest.OperationURLParameter = { parameterPath: "operationId", mapper: { required: true, serializedName: "operationId", type: { name: "String" } } }; export const osType: msRest.OperationQueryParameter = { parameterPath: [ "options", "osType" ], mapper: { serializedName: "osType", type: { name: "String" } } }; export const osTypeSelected: msRest.OperationQueryParameter = { parameterPath: [ "options", "osTypeSelected" ], mapper: { serializedName: "osTypeSelected", type: { name: "String" } } }; export const premierAddOnName: msRest.OperationURLParameter = { parameterPath: "premierAddOnName", mapper: { required: true, serializedName: "premierAddOnName", type: { name: "String" } } }; export const processId: msRest.OperationURLParameter = { parameterPath: "processId", mapper: { required: true, serializedName: "processId", type: { name: "String" } } }; export const publicCertificateName: msRest.OperationURLParameter = { parameterPath: "publicCertificateName", mapper: { required: true, serializedName: "publicCertificateName", type: { name: "String" } } }; export const recommendationId: msRest.OperationQueryParameter = { parameterPath: [ "options", "recommendationId" ], mapper: { serializedName: "recommendationId", type: { name: "String" } } }; export const relayName: msRest.OperationURLParameter = { parameterPath: "relayName", mapper: { required: true, serializedName: "relayName", type: { name: "String" } } }; export const resourceGroupName: msRest.OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { required: true, serializedName: "resourceGroupName", constraints: { MaxLength: 90, MinLength: 1, Pattern: /^[-\w\._\(\)]+[^\.]$/ }, type: { name: "String" } } }; export const routeName: msRest.OperationURLParameter = { parameterPath: "routeName", mapper: { required: true, serializedName: "routeName", type: { name: "String" } } }; export const sasUrl: msRest.OperationQueryParameter = { parameterPath: [ "options", "sasUrl" ], mapper: { serializedName: "sasUrl", type: { name: "String" } } }; export const siteExtensionId: msRest.OperationURLParameter = { parameterPath: "siteExtensionId", mapper: { required: true, serializedName: "siteExtensionId", type: { name: "String" } } }; export const siteName: msRest.OperationURLParameter = { parameterPath: "siteName", mapper: { required: true, serializedName: "siteName", type: { name: "String" } } }; export const skipToken: msRest.OperationQueryParameter = { parameterPath: [ "options", "skipToken" ], mapper: { serializedName: "$skipToken", type: { name: "String" } } }; export const sku: msRest.OperationQueryParameter = { parameterPath: [ "options", "sku" ], mapper: { serializedName: "sku", type: { name: "String" } } }; export const slot: msRest.OperationURLParameter = { parameterPath: "slot", mapper: { required: true, serializedName: "slot", type: { name: "String" } } }; export const snapshotId: msRest.OperationURLParameter = { parameterPath: "snapshotId", mapper: { required: true, serializedName: "snapshotId", type: { name: "String" } } }; export const softRestart: msRest.OperationQueryParameter = { parameterPath: [ "options", "softRestart" ], mapper: { serializedName: "softRestart", type: { name: "Boolean" } } }; export const sourceControlType: msRest.OperationURLParameter = { parameterPath: "sourceControlType", mapper: { required: true, serializedName: "sourceControlType", type: { name: "String" } } }; export const subscriptionId: msRest.OperationURLParameter = { parameterPath: "subscriptionId", mapper: { required: true, serializedName: "subscriptionId", type: { name: "String" } } }; export const subscriptionName: msRest.OperationQueryParameter = { parameterPath: "subscriptionName", mapper: { required: true, serializedName: "subscriptionName", type: { name: "String" } } }; export const synchronous: msRest.OperationQueryParameter = { parameterPath: [ "options", "synchronous" ], mapper: { serializedName: "synchronous", type: { name: "Boolean" } } }; export const threadId: msRest.OperationURLParameter = { parameterPath: "threadId", mapper: { required: true, serializedName: "threadId", type: { name: "String" } } }; export const top: msRest.OperationQueryParameter = { parameterPath: [ "options", "top" ], mapper: { serializedName: "$top", type: { name: "String" } } }; export const updateSeen: msRest.OperationQueryParameter = { parameterPath: [ "options", "updateSeen" ], mapper: { serializedName: "updateSeen", type: { name: "Boolean" } } }; export const view: msRest.OperationURLParameter = { parameterPath: "view", mapper: { required: true, serializedName: "view", type: { name: "String" } } }; export const vnetName: msRest.OperationURLParameter = { parameterPath: "vnetName", mapper: { required: true, serializedName: "vnetName", type: { name: "String" } } }; export const webJobName: msRest.OperationURLParameter = { parameterPath: "webJobName", mapper: { required: true, serializedName: "webJobName", type: { name: "String" } } }; export const workerName: msRest.OperationURLParameter = { parameterPath: "workerName", mapper: { required: true, serializedName: "workerName", type: { name: "String" } } }; export const xenonWorkersEnabled: msRest.OperationQueryParameter = { parameterPath: [ "options", "xenonWorkersEnabled" ], mapper: { serializedName: "xenonWorkersEnabled", type: { name: "Boolean" } } };
the_stack
import detectIndent from 'detect-indent'; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! import detectNewline from 'detect-newline'; import fs from 'fs-extra'; import * as path from 'path'; import R from 'ramda'; import stringifyPackage from 'stringify-package'; import { DEPENDENCIES_FIELDS, PACKAGE_JSON } from '../../constants'; import logger from '../../logger/logger'; import componentIdToPackageName from '../../utils/bit/component-id-to-package-name'; import { PathOsBased, PathOsBasedAbsolute, PathOsBasedRelative, PathRelative } from '../../utils/path'; import Component from './consumer-component'; import PackageJsonVinyl from './package-json-vinyl'; /** * when a package.json file is loaded, we save the indentation and the type of newline it uses, so * then we could preserve it later on while writing the file. this is same process used by NPM when * writing the package.json file */ export default class PackageJsonFile { packageJsonObject: Record<string, any>; fileExist: boolean; filePath: PathOsBasedRelative; workspaceDir: PathOsBasedAbsolute | null | undefined; indent: string | null | undefined; // default when writing (in stringifyPackage) is " ". (two spaces). newline: string | null | undefined; // whether "\n" or "\r\n", default when writing (in stringifyPackage) is "\n" constructor({ filePath, packageJsonObject = {}, fileExist, workspaceDir, indent, newline, }: { filePath: PathOsBasedRelative; packageJsonObject?: Record<string, any>; fileExist: boolean; workspaceDir?: PathOsBasedAbsolute; indent?: string; newline?: string; }) { this.filePath = filePath; this.packageJsonObject = packageJsonObject; this.fileExist = fileExist; this.workspaceDir = workspaceDir; this.indent = indent; this.newline = newline; } async write() { if (!this.workspaceDir) throw new Error('PackageJsonFile is unable to write, workspaceDir is not defined'); const pathToWrite = path.join(this.workspaceDir, this.filePath); logger.debug(`package-json-file.write, path ${pathToWrite}`); const packageJsonStr = stringifyPackage(this.packageJsonObject, this.indent, this.newline); await fs.outputFile(pathToWrite, packageJsonStr); this.fileExist = true; } /** * load from the given dir, if not exist, don't throw an error, just set packageJsonObject as an * empty object */ // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! static async load(workspaceDir: PathOsBasedAbsolute, componentDir?: PathRelative = '.'): Promise<PackageJsonFile> { const filePath = composePath(componentDir); const filePathAbsolute = path.join(workspaceDir, filePath); const packageJsonStr = await PackageJsonFile.getPackageJsonStrIfExist(filePathAbsolute); if (!packageJsonStr) { return new PackageJsonFile({ filePath, fileExist: false, workspaceDir }); } const packageJsonObject = PackageJsonFile.parsePackageJsonStr(packageJsonStr, componentDir); const indent = detectIndent(packageJsonStr).indent; const newline = detectNewline(packageJsonStr); return new PackageJsonFile({ filePath, packageJsonObject, fileExist: true, workspaceDir, indent, newline }); } static async reset(workspaceDir: PathOsBasedAbsolute) { const pkgJsonFile = await PackageJsonFile.load(workspaceDir); if (pkgJsonFile.fileExist) { pkgJsonFile.removeProperty('bit'); await pkgJsonFile.write(); } } static loadSync(workspaceDir: PathOsBasedAbsolute, componentDir: PathRelative = '.'): PackageJsonFile { const filePath = composePath(componentDir); const filePathAbsolute = path.join(workspaceDir, filePath); const packageJsonStr = PackageJsonFile.getPackageJsonStrIfExistSync(filePathAbsolute); if (!packageJsonStr) { return new PackageJsonFile({ filePath, fileExist: false, workspaceDir }); } const packageJsonObject = PackageJsonFile.parsePackageJsonStr(packageJsonStr, componentDir); const indent = detectIndent(packageJsonStr).indent; const newline = detectNewline(packageJsonStr); return new PackageJsonFile({ filePath, packageJsonObject, fileExist: true, workspaceDir, indent, newline }); } static loadFromPathSync(workspaceDir: PathOsBasedAbsolute, pathToLoad: string) { const filePath = composePath(pathToLoad); const filePathAbsolute = path.join(workspaceDir, filePath); const packageJsonStr = PackageJsonFile.getPackageJsonStrIfExistSync(filePathAbsolute); if (!packageJsonStr) { return new PackageJsonFile({ filePath, fileExist: false, workspaceDir }); } const packageJsonObject = PackageJsonFile.parsePackageJsonStr(packageJsonStr, pathToLoad); return new PackageJsonFile({ filePath, packageJsonObject, fileExist: true, workspaceDir }); } static loadFromCapsuleSync(capsuleRootDir: string) { const filePath = composePath('.'); const filePathAbsolute = path.join(capsuleRootDir, filePath); const packageJsonStr = PackageJsonFile.getPackageJsonStrIfExistSync(filePathAbsolute); if (!packageJsonStr) { throw new Error(`capsule ${capsuleRootDir} is missing package.json`); } const packageJsonObject = PackageJsonFile.parsePackageJsonStr(packageJsonStr, filePath); return new PackageJsonFile({ filePath, packageJsonObject, fileExist: true, workspaceDir: capsuleRootDir }); } static createFromComponent( componentDir: PathRelative, component: Component, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! excludeRegistryPrefix? = false, addDefaultScopeToCompId? = false, // for the capsule, we want the default-scope because it gets published addExportProperty? = false ): PackageJsonFile { const filePath = composePath(componentDir); const name = componentIdToPackageName({ withPrefix: !excludeRegistryPrefix, ...component, id: component.id }); const componentIdWithDefaultScope = component.id.hasScope() || !addDefaultScopeToCompId ? component.id : component.id.changeScope(component.defaultScope); const packageJsonObject = { name, version: component.version, homepage: component._getHomepage(), main: component.mainFile, // Used for determine that a package is a component // Used when resolve dependencies to identify that some package should be treated as component // TODO: replace by better way to identify that something is a component for sure // TODO: Maybe need to add the binding prefix here componentId: componentIdWithDefaultScope.serialize(), dependencies: { ...component.packageDependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.compilerPackageDependencies.dependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.testerPackageDependencies.dependencies, }, devDependencies: { ...component.devPackageDependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.compilerPackageDependencies.devDependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.testerPackageDependencies.devDependencies, }, peerDependencies: { ...component.peerPackageDependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.compilerPackageDependencies.peerDependencies, // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! ...component.testerPackageDependencies.peerDependencies, }, license: `SEE LICENSE IN ${!R.isEmpty(component.license) ? 'LICENSE' : 'UNLICENSED'}`, }; // @ts-ignore if (addExportProperty) packageJsonObject.exported = component.id.hasScope(); if (!packageJsonObject.homepage) delete packageJsonObject.homepage; return new PackageJsonFile({ filePath, packageJsonObject, fileExist: false }); } toVinylFile(): PackageJsonVinyl { return PackageJsonVinyl.load({ base: path.dirname(this.filePath), path: this.filePath, content: this.packageJsonObject, indent: this.indent, newline: this.newline, }); } addDependencies(dependencies: Record<string, any>) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.packageJsonObject.dependencies = Object.assign({}, this.packageJsonObject.dependencies, dependencies); } addDevDependencies(dependencies: Record<string, any>) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.packageJsonObject.devDependencies = Object.assign({}, this.packageJsonObject.devDependencies, dependencies); } removeDependency(dependency: string) { delete this.packageJsonObject.dependencies[dependency]; } copyPeerDependenciesToDev() { const devDeps = this.packageJsonObject.devDependencies || {}; const peerDeps = this.packageJsonObject.peerDependencies || {}; this.packageJsonObject.devDependencies = { ...devDeps, ...peerDeps }; } replaceDependencies(dependencies: Record<string, any>) { Object.keys(dependencies).forEach((dependency) => { DEPENDENCIES_FIELDS.forEach((dependencyField) => { if (this.packageJsonObject[dependencyField] && this.packageJsonObject[dependencyField][dependency]) { this.packageJsonObject[dependencyField][dependency] = dependencies[dependency]; } }); }); } addOrUpdateProperty(propertyName: string, propertyValue: any): void { this.packageJsonObject[propertyName] = propertyValue; } removeProperty(propertyName: string) { delete this.packageJsonObject[propertyName]; } getProperty(propertyName: string): any { return this.packageJsonObject[propertyName]; } setPackageManager(packageManager: string | undefined) { if (!packageManager) return; this.packageJsonObject.packageManager = packageManager; } mergePackageJsonObject(packageJsonObject: Record<string, any> | null | undefined): void { if (!packageJsonObject || R.isEmpty(packageJsonObject)) return; this.packageJsonObject = Object.assign(this.packageJsonObject, packageJsonObject); } clone(): PackageJsonFile { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const clone = new PackageJsonFile(this); clone.packageJsonObject = R.clone(this.packageJsonObject); return clone; } static propsNonUserChangeable() { return ['name', 'version', 'main', 'dependencies', 'devDependencies', 'peerDependencies', 'license', 'bit']; } static parsePackageJsonStr(str: string, dir: string) { try { return JSON.parse(str); } catch (err: any) { throw new Error(`failed parsing package.json file at ${dir}. original error: ${err.message}`); } } static async getPackageJsonStrIfExist(filePath: PathOsBased) { try { return await fs.readFile(filePath, 'utf-8'); } catch (err: any) { if (err.code === 'ENOENT') { return null; // file not found } throw err; } } static getPackageJsonStrIfExistSync(filePath: PathOsBased) { try { return fs.readFileSync(filePath, 'utf-8'); } catch (err: any) { if (err.code === 'ENOENT') { return null; // file not found } throw err; } } } function composePath(componentRootFolder: string) { return path.join(componentRootFolder, PACKAGE_JSON); }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Group } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ApiManagementClient } from "../apiManagementClient"; import { GroupContract, GroupListByServiceNextOptionalParams, GroupListByServiceOptionalParams, GroupListByServiceResponse, GroupGetEntityTagOptionalParams, GroupGetEntityTagResponse, GroupGetOptionalParams, GroupGetResponse, GroupCreateParameters, GroupCreateOrUpdateOptionalParams, GroupCreateOrUpdateResponse, GroupUpdateParameters, GroupUpdateOptionalParams, GroupUpdateResponse, GroupDeleteOptionalParams, GroupListByServiceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Group operations. */ export class GroupImpl implements Group { private readonly client: ApiManagementClient; /** * Initialize a new instance of the class Group class. * @param client Reference to the service client */ constructor(client: ApiManagementClient) { this.client = client; } /** * Lists a collection of groups defined within a service instance. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ public listByService( resourceGroupName: string, serviceName: string, options?: GroupListByServiceOptionalParams ): PagedAsyncIterableIterator<GroupContract> { const iter = this.listByServicePagingAll( resourceGroupName, serviceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByServicePagingPage( resourceGroupName, serviceName, options ); } }; } private async *listByServicePagingPage( resourceGroupName: string, serviceName: string, options?: GroupListByServiceOptionalParams ): AsyncIterableIterator<GroupContract[]> { let result = await this._listByService( resourceGroupName, serviceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByServiceNext( resourceGroupName, serviceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByServicePagingAll( resourceGroupName: string, serviceName: string, options?: GroupListByServiceOptionalParams ): AsyncIterableIterator<GroupContract> { for await (const page of this.listByServicePagingPage( resourceGroupName, serviceName, options )) { yield* page; } } /** * Lists a collection of groups defined within a service instance. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ private _listByService( resourceGroupName: string, serviceName: string, options?: GroupListByServiceOptionalParams ): Promise<GroupListByServiceResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, listByServiceOperationSpec ); } /** * Gets the entity state (Etag) version of the group specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param groupId Group identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ getEntityTag( resourceGroupName: string, serviceName: string, groupId: string, options?: GroupGetEntityTagOptionalParams ): Promise<GroupGetEntityTagResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, groupId, options }, getEntityTagOperationSpec ); } /** * Gets the details of the group specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param groupId Group identifier. Must be unique in the current API Management service instance. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, groupId: string, options?: GroupGetOptionalParams ): Promise<GroupGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, groupId, options }, getOperationSpec ); } /** * Creates or Updates a group. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param groupId Group identifier. Must be unique in the current API Management service instance. * @param parameters Create parameters. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, serviceName: string, groupId: string, parameters: GroupCreateParameters, options?: GroupCreateOrUpdateOptionalParams ): Promise<GroupCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, groupId, parameters, options }, createOrUpdateOperationSpec ); } /** * Updates the details of the group specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param groupId Group identifier. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param parameters Update parameters. * @param options The options parameters. */ update( resourceGroupName: string, serviceName: string, groupId: string, ifMatch: string, parameters: GroupUpdateParameters, options?: GroupUpdateOptionalParams ): Promise<GroupUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, groupId, ifMatch, parameters, options }, updateOperationSpec ); } /** * Deletes specific group of the API Management service instance. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param groupId Group identifier. Must be unique in the current API Management service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param options The options parameters. */ delete( resourceGroupName: string, serviceName: string, groupId: string, ifMatch: string, options?: GroupDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, groupId, ifMatch, options }, deleteOperationSpec ); } /** * ListByServiceNext * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param nextLink The nextLink from the previous successful call to the ListByService method. * @param options The options parameters. */ private _listByServiceNext( resourceGroupName: string, serviceName: string, nextLink: string, options?: GroupListByServiceNextOptionalParams ): Promise<GroupListByServiceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, nextLink, options }, listByServiceNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByServiceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GroupCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.top, Parameters.skip, Parameters.apiVersion ], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const getEntityTagOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups/{groupId}", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.GroupGetEntityTagHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.groupId ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups/{groupId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GroupContract, headersMapper: Mappers.GroupGetHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.groupId ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups/{groupId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.GroupContract, headersMapper: Mappers.GroupCreateOrUpdateHeaders }, 201: { bodyMapper: Mappers.GroupContract, headersMapper: Mappers.GroupCreateOrUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters36, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.groupId ], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch ], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups/{groupId}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.GroupContract, headersMapper: Mappers.GroupUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters37, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.groupId ], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch1 ], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/groups/{groupId}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.groupId ], headerParameters: [Parameters.accept, Parameters.ifMatch1], serializer }; const listByServiceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GroupCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.top, Parameters.skip, Parameters.apiVersion ], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import * as initDebug from 'debug'; import * as Token from 'token-types'; import * as util from '../common/Util'; import { AttachedPictureType, ID3v2MajorVersion, TextEncodingToken } from './ID3v2Token'; import { IWarningCollector } from '../common/MetadataCollector'; import { Genres } from '../id3v1/ID3v1Parser'; const debug = initDebug('music-metadata:id3v2:frame-parser'); interface IOut { language?: string, description?: string, text?: string, } interface IPicture { type?: string, description?: string; format?: string, data?: Uint8Array; } const defaultEnc: util.StringEncoding = 'latin1'; // latin1 == iso-8859-1; export function parseGenre(origVal: string): string[] { // match everything inside parentheses const genres = []; let code: string; let word: string = ''; for (const c of origVal) { if (typeof code === 'string') { if (c === '(' && code === '') { word += '('; code = undefined; } else if (c === ')') { if (word !== '') { genres.push(word); word = ''; } const genre = parseGenreCode(code); if (genre) { genres.push(genre); } code = undefined; } else code += c; } else if (c === '(') { code = ''; } else { word += c; } } if (word) { if (genres.length === 0 && word.match(/^\d*$/)) { word = Genres[word]; } genres.push(word); } return genres; } function parseGenreCode(code: string): string { if (code === 'RX') return 'Remix'; if (code === 'CR') return 'Cover'; if (code.match(/^\d*$/)) { return Genres[code]; } } export class FrameParser { /** * Create id3v2 frame parser * @param major - Major version, e.g. (4) for id3v2.4 * @param warningCollector - Used to collect decode issue */ constructor(private major: ID3v2MajorVersion, private warningCollector: IWarningCollector) { } public readData(b: Buffer, type: string, includeCovers: boolean) { if (b.length === 0) { this.warningCollector.addWarning(`id3v2.${this.major} header has empty tag type=${type}`); return; } const {encoding, bom} = TextEncodingToken.get(b, 0); const length = b.length; let offset = 0; let output: any = []; // ToDo const nullTerminatorLength = FrameParser.getNullTerminatorLength(encoding); let fzero: number; const out: IOut = {}; debug(`Parsing tag type=${type}, encoding=${encoding}, bom=${bom}`); switch (type !== 'TXXX' && type[0] === 'T' ? 'T*' : type) { case 'T*': // 4.2.1. Text information frames - details case 'IPLS': // v2.3: Involved people list case 'MVIN': case 'MVNM': case 'PCS': case 'PCST': const text = util.decodeString(b.slice(1), encoding).replace(/\x00+$/, ''); switch (type) { case 'TMCL': // Musician credits list case 'TIPL': // Involved people list case 'IPLS': // Involved people list output = this.splitValue(type, text); output = FrameParser.functionList(output); break; case 'TRK': case 'TRCK': case 'TPOS': output = text; break; case 'TCOM': case 'TEXT': case 'TOLY': case 'TOPE': case 'TPE1': case 'TSRC': // id3v2.3 defines that TCOM, TEXT, TOLY, TOPE & TPE1 values are separated by / output = this.splitValue(type, text); break; case 'TCO': case 'TCON': output = this.splitValue(type, text).map(v => parseGenre(v)).reduce((acc, val) => acc.concat(val), []); break; case 'PCS': case 'PCST': // TODO: Why `default` not results `1` but `''`? output = this.major >= 4 ? this.splitValue(type, text) : [text]; output = (Array.isArray(output) && output[0] === '') ? 1 : 0; break; default: output = this.major >= 4 ? this.splitValue(type, text) : [text]; } break; case 'TXXX': output = FrameParser.readIdentifierAndData(b, offset + 1, length, encoding); output = { description: output.id, text: this.splitValue(type, util.decodeString(output.data, encoding).replace(/\x00+$/, '')) }; break; case 'PIC': case 'APIC': if (includeCovers) { const pic: IPicture = {}; offset += 1; switch (this.major) { case 2: pic.format = util.decodeString(b.slice(offset, offset + 3), 'latin1'); // 'latin1'; // latin1 == iso-8859-1; offset += 3; break; case 3: case 4: fzero = util.findZero(b, offset, length, defaultEnc); pic.format = util.decodeString(b.slice(offset, fzero), defaultEnc); offset = fzero + 1; break; default: throw new Error('Warning: unexpected major versionIndex: ' + this.major); } pic.format = FrameParser.fixPictureMimeType(pic.format); pic.type = AttachedPictureType[b[offset]]; offset += 1; fzero = util.findZero(b, offset, length, encoding); pic.description = util.decodeString(b.slice(offset, fzero), encoding); offset = fzero + nullTerminatorLength; pic.data = Buffer.from(b.slice(offset, length)); output = pic; } break; case 'CNT': case 'PCNT': output = Token.UINT32_BE.get(b, 0); break; case 'SYLT': // skip text encoding (1 byte), // language (3 bytes), // time stamp format (1 byte), // content tagTypes (1 byte), // content descriptor (1 byte) offset += 7; output = []; while (offset < length) { const txt = b.slice(offset, offset = util.findZero(b, offset, length, encoding)); offset += 5; // push offset forward one + 4 byte timestamp output.push(util.decodeString(txt, encoding)); } break; case 'ULT': case 'USLT': case 'COM': case 'COMM': offset += 1; out.language = util.decodeString(b.slice(offset, offset + 3), defaultEnc); offset += 3; fzero = util.findZero(b, offset, length, encoding); out.description = util.decodeString(b.slice(offset, fzero), encoding); offset = fzero + nullTerminatorLength; out.text = util.decodeString(b.slice(offset, length), encoding).replace(/\x00+$/, ''); output = [out]; break; case 'UFID': output = FrameParser.readIdentifierAndData(b, offset, length, defaultEnc); output = {owner_identifier: output.id, identifier: output.data}; break; case 'PRIV': // private frame output = FrameParser.readIdentifierAndData(b, offset, length, defaultEnc); output = {owner_identifier: output.id, data: output.data}; break; case 'POPM': // Popularimeter fzero = util.findZero(b, offset, length, defaultEnc); const email = util.decodeString(b.slice(offset, fzero), defaultEnc); offset = fzero + 1; const dataLen = length - offset; output = { email, rating: b.readUInt8(offset), counter: dataLen >= 5 ? b.readUInt32BE(offset + 1) : undefined }; break; case 'GEOB': { // General encapsulated object fzero = util.findZero(b, offset + 1, length, encoding); const mimeType = util.decodeString(b.slice(offset + 1, fzero), defaultEnc); offset = fzero + 1; fzero = util.findZero(b, offset, length - offset, encoding); const filename = util.decodeString(b.slice(offset, fzero), defaultEnc); offset = fzero + 1; fzero = util.findZero(b, offset, length - offset, encoding); const description = util.decodeString(b.slice(offset, fzero), defaultEnc); output = { type: mimeType, filename, description, data: b.slice(offset + 1, length) }; break; } // W-Frames: case 'WCOM': case 'WCOP': case 'WOAF': case 'WOAR': case 'WOAS': case 'WORS': case 'WPAY': case 'WPUB': // Decode URL output = util.decodeString(b.slice(offset, fzero), defaultEnc); break; case 'WXXX': { // Decode URL fzero = util.findZero(b, offset + 1, length, encoding); const description = util.decodeString(b.slice(offset + 1, fzero), encoding); offset = fzero + (encoding === 'utf16le' ? 2 : 1); output = {description, url: util.decodeString(b.slice(offset, length), defaultEnc)}; break; } case 'WFD': case 'WFED': output = util.decodeString(b.slice(offset + 1, util.findZero(b, offset + 1, length, encoding)), encoding); break; case 'MCDI': { // Music CD identifier output = b.slice(0, length); break; } default: debug('Warning: unsupported id3v2-tag-type: ' + type); break; } return output; } protected static fixPictureMimeType(pictureType: string): string { pictureType = pictureType.toLocaleLowerCase(); switch (pictureType) { case 'jpg': return 'image/jpeg'; case 'png': return 'image/png'; } return pictureType; } /** * Converts TMCL (Musician credits list) or TIPL (Involved people list) * @param entries */ private static functionList(entries: string[]): { [index: string]: string[] } { const res: { [index: string]: string[] } = {}; for (let i = 0; i + 1 < entries.length; i += 2) { const names: string[] = entries[i + 1].split(','); res[entries[i]] = res.hasOwnProperty(entries[i]) ? res[entries[i]].concat(names) : names; } return res; } /** * id3v2.4 defines that multiple T* values are separated by 0x00 * id3v2.3 defines that TCOM, TEXT, TOLY, TOPE & TPE1 values are separated by / * @param tag - Tag name * @param text - Concatenated tag value * @returns Split tag value */ private splitValue(tag: string, text: string): string[] { let values: string[]; if (this.major < 4) { values = text.split(/\x00/g); if (values.length > 1) { this.warningCollector.addWarning(`ID3v2.${this.major} ${tag} uses non standard null-separator.`); } else { values = text.split(/\//g); } } else { values = text.split(/\x00/g); } return FrameParser.trimArray(values); } private static trimArray(values: string[]): string[] { return values.map(value => value.replace(/\x00+$/, '').trim()); } private static readIdentifierAndData(b: Buffer, offset: number, length: number, encoding: util.StringEncoding): { id: string, data: Uint8Array } { const fzero = util.findZero(b, offset, length, encoding); const id = util.decodeString(b.slice(offset, fzero), encoding); offset = fzero + FrameParser.getNullTerminatorLength(encoding); return {id, data: b.slice(offset, length)}; } private static getNullTerminatorLength(enc: util.StringEncoding): number { return enc === 'utf16le' ? 2 : 1; } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * @interface * An interface representing AvailableOperationDisplay. * An operation available at the listed Azure resource provider. * */ export interface AvailableOperationDisplay { /** * @member {string} [provider] Name of the operation provider. */ provider?: string; /** * @member {string} [resource] Name of the resource on which the operation is * available. */ resource?: string; /** * @member {string} [operation] Name of the available operation. */ operation?: string; /** * @member {string} [description] Description of the available operation. */ description?: string; } /** * @interface * An interface representing ErrorDetailsModel. * Error model details information * */ export interface ErrorDetailsModel { /** * @member {string} code */ code: string; /** * @member {string} message Error message. */ message: string; } /** * @interface * An interface representing ErrorErrorModel. * Error model information * */ export interface ErrorErrorModel { /** * @member {string} code */ code: string; /** * @member {string} [message] Error message. */ message?: string; /** * @member {string} [innerError] */ innerError?: string; /** * @member {ErrorDetailsModel[]} [details] List of error message details. */ details?: ErrorDetailsModel[]; } /** * @interface * An interface representing ErrorModel. * The error details. * */ export interface ErrorModel { /** * @member {ErrorErrorModel} error Error model information */ error: ErrorErrorModel; } /** * @interface * An interface representing OperationResult. * List of operations available at the listed Azure resource provider. * */ export interface OperationResult { /** * @member {string} [name] The name of the operation. */ name?: string; /** * @member {AvailableOperationDisplay} [display] The object that represents * the operation. */ display?: AvailableOperationDisplay; /** * @member {string} [origin] Origin result */ origin?: string; /** * @member {string} [nextLink] The URL to use for getting the next set of * results. */ nextLink?: string; } /** * @interface * An interface representing ProvisionedResourceProperties. * Describes common properties of a provisioned resource. * */ export interface ProvisionedResourceProperties { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; } /** * @interface * An interface representing Resource. * The resource model definition for Azure Resource Manager resource. * * @extends BaseResource */ export interface Resource extends BaseResource { /** * @member {string} [id] Fully qualified identifier for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The name of the resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [type] The type of the resource. Ex- * Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; } /** * @interface * An interface representing ProxyResource. * The resource model definition for Azure Resource Manager proxy resource. It * will have everything other than required location and tags. * * @extends Resource */ export interface ProxyResource extends Resource { } /** * @interface * An interface representing ManagedProxyResource. * The resource model definition for Azure Resource Manager proxy resource. It * will have everything other than required location and tags. This proxy * resource is explicitly created or updated by including it in the parent * resource. * * @extends BaseResource */ export interface ManagedProxyResource extends BaseResource { /** * @member {string} [id] Fully qualified identifier for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The name of the resource */ name?: string; /** * @member {string} [type] The type of the resource. Ex- * Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; } /** * @interface * An interface representing TrackedResource. * The resource model definition for Azure Resource Manager tracked top-level * resource. * * @extends Resource */ export interface TrackedResource extends Resource { /** * @member {{ [propertyName: string]: string }} [tags] Resource tags. */ tags?: { [propertyName: string]: string }; /** * @member {string} location The geo-location where the resource lives */ location: string; } /** * Contains the possible cases for SecretResourcePropertiesBase. */ export type SecretResourcePropertiesBaseUnion = SecretResourcePropertiesBase | SecretResourcePropertiesUnion; /** * @interface * An interface representing SecretResourcePropertiesBase. * This type describes the properties of a secret resource, including its kind. * */ export interface SecretResourcePropertiesBase { /** * @member {string} kind Polymorphic Discriminator */ kind: "SecretResourcePropertiesBase"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; } /** * Contains the possible cases for SecretResourceProperties. */ export type SecretResourcePropertiesUnion = SecretResourceProperties | InlinedValueSecretResourceProperties; /** * @interface * An interface representing SecretResourceProperties. * Describes the properties of a secret resource. * */ export interface SecretResourceProperties { /** * @member {string} kind Polymorphic Discriminator */ kind: "SecretResourceProperties"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the secret. */ description?: string; /** * @member {ResourceStatus} [status] Status of the resource. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the secret. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {string} [contentType] The type of the content stored in the * secret value. The value of this property is opaque to Service Fabric. Once * set, the value of this property cannot be changed. */ contentType?: string; } /** * @interface * An interface representing InlinedValueSecretResourceProperties. * Describes the properties of a secret resource whose value is provided * explicitly as plaintext. The secret resource may have multiple values, each * being uniquely versioned. The secret value of each version is stored * encrypted, and delivered as plaintext into the context of applications * referencing it. * */ export interface InlinedValueSecretResourceProperties { /** * @member {string} kind Polymorphic Discriminator */ kind: "inlinedValue"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the secret. */ description?: string; /** * @member {ResourceStatus} [status] Status of the resource. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the secret. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {string} [contentType] The type of the content stored in the * secret value. The value of this property is opaque to Service Fabric. Once * set, the value of this property cannot be changed. */ contentType?: string; } /** * @interface * An interface representing SecretResourceDescription. * This type describes a secret resource. * * @extends TrackedResource */ export interface SecretResourceDescription extends TrackedResource { /** * @member {SecretResourcePropertiesUnion} properties Describes the * properties of a secret resource. */ properties: SecretResourcePropertiesUnion; } /** * @interface * An interface representing SecretValue. * This type represents the unencrypted value of the secret. * */ export interface SecretValue { /** * @member {string} [value] The actual value of the secret. */ value?: string; } /** * @interface * An interface representing SecretValueProperties. * This type describes properties of secret value resource. * */ export interface SecretValueProperties { /** * @member {string} [value] The actual value of the secret. */ value?: string; } /** * @interface * An interface representing SecretValueResourceDescription. * This type describes a value of a secret resource. The name of this resource * is the version identifier corresponding to this secret value. * * @extends TrackedResource */ export interface SecretValueResourceDescription extends TrackedResource { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [value] The actual value of the secret. */ value?: string; } /** * @interface * An interface representing VolumeProviderParametersAzureFile. * This type describes a volume provided by an Azure Files file share. * */ export interface VolumeProviderParametersAzureFile { /** * @member {string} accountName Name of the Azure storage account for the * File Share. */ accountName: string; /** * @member {string} [accountKey] Access key of the Azure storage account for * the File Share. */ accountKey?: string; /** * @member {string} shareName Name of the Azure Files file share that * provides storage for the volume. */ shareName: string; } /** * @interface * An interface representing VolumeProperties. * Describes properties of a volume resource. * */ export interface VolumeProperties { /** * @member {string} [description] User readable description of the volume. */ description?: string; /** * @member {ResourceStatus} [status] Status of the volume. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the volume. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {VolumeProviderParametersAzureFile} [azureFileParameters] This * type describes a volume provided by an Azure Files file share. */ azureFileParameters?: VolumeProviderParametersAzureFile; } /** * @interface * An interface representing VolumeReference. * Describes a reference to a volume resource. * */ export interface VolumeReference { /** * @member {string} name Name of the volume being referenced. */ name: string; /** * @member {boolean} [readOnly] The flag indicating whether the volume is * read only. Default is 'false'. */ readOnly?: boolean; /** * @member {string} destinationPath The path within the container at which * the volume should be mounted. Only valid path characters are allowed. */ destinationPath: string; } /** * Contains the possible cases for ApplicationScopedVolumeCreationParameters. */ export type ApplicationScopedVolumeCreationParametersUnion = ApplicationScopedVolumeCreationParameters | ApplicationScopedVolumeCreationParametersServiceFabricVolumeDisk; /** * @interface * An interface representing ApplicationScopedVolumeCreationParameters. * Describes parameters for creating application-scoped volumes. * */ export interface ApplicationScopedVolumeCreationParameters { /** * @member {string} kind Polymorphic Discriminator */ kind: "ApplicationScopedVolumeCreationParameters"; /** * @member {string} [description] User readable description of the volume. */ description?: string; } /** * @interface * An interface representing ApplicationScopedVolume. * Describes a volume whose lifetime is scoped to the application's lifetime. * * @extends VolumeReference */ export interface ApplicationScopedVolume extends VolumeReference { /** * @member {ApplicationScopedVolumeCreationParametersUnion} * creationParameters Describes parameters for creating application-scoped * volumes. */ creationParameters: ApplicationScopedVolumeCreationParametersUnion; } /** * @interface * An interface representing ApplicationScopedVolumeCreationParametersServiceFabricVolumeDisk. * Describes parameters for creating application-scoped volumes provided by * Service Fabric Volume Disks * */ export interface ApplicationScopedVolumeCreationParametersServiceFabricVolumeDisk { /** * @member {string} kind Polymorphic Discriminator */ kind: "ServiceFabricVolumeDisk"; /** * @member {string} [description] User readable description of the volume. */ description?: string; /** * @member {SizeTypes} sizeDisk Volume size. Possible values include: * 'Small', 'Medium', 'Large' */ sizeDisk: SizeTypes; } /** * @interface * An interface representing VolumeResourceDescription. * This type describes a volume resource. * * @extends TrackedResource */ export interface VolumeResourceDescription extends TrackedResource { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the volume. */ description?: string; /** * @member {ResourceStatus} [status] Status of the volume. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the volume. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {VolumeProviderParametersAzureFile} [azureFileParameters] This * type describes a volume provided by an Azure Files file share. */ azureFileParameters?: VolumeProviderParametersAzureFile; } /** * Contains the possible cases for NetworkResourcePropertiesBase. */ export type NetworkResourcePropertiesBaseUnion = NetworkResourcePropertiesBase | NetworkResourcePropertiesUnion; /** * @interface * An interface representing NetworkResourcePropertiesBase. * This type describes the properties of a network resource, including its * kind. * */ export interface NetworkResourcePropertiesBase { /** * @member {string} kind Polymorphic Discriminator */ kind: "NetworkResourcePropertiesBase"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; } /** * Contains the possible cases for NetworkResourceProperties. */ export type NetworkResourcePropertiesUnion = NetworkResourceProperties | LocalNetworkResourceProperties; /** * @interface * An interface representing NetworkResourceProperties. * Describes properties of a network resource. * */ export interface NetworkResourceProperties { /** * @member {string} kind Polymorphic Discriminator */ kind: "NetworkResourceProperties"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the network. */ description?: string; /** * @member {ResourceStatus} [status] Status of the network. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the network. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; } /** * @interface * An interface representing LocalNetworkResourceProperties. * Information about a Service Fabric container network local to a single * Service Fabric cluster. * */ export interface LocalNetworkResourceProperties { /** * @member {string} kind Polymorphic Discriminator */ kind: "Local"; /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the network. */ description?: string; /** * @member {ResourceStatus} [status] Status of the network. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the network. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {string} [networkAddressPrefix] Address space for the local * container network. */ networkAddressPrefix?: string; } /** * @interface * An interface representing EndpointRef. * Describes a reference to a service endpoint. * */ export interface EndpointRef { /** * @member {string} [name] Name of the endpoint. */ name?: string; } /** * @interface * An interface representing NetworkRef. * Describes a network reference in a service. * */ export interface NetworkRef { /** * @member {string} [name] Name of the network */ name?: string; /** * @member {EndpointRef[]} [endpointRefs] A list of endpoints that are * exposed on this network. */ endpointRefs?: EndpointRef[]; } /** * @interface * An interface representing NetworkResourceDescription. * This type describes a network resource. * * @extends TrackedResource */ export interface NetworkResourceDescription extends TrackedResource { /** * @member {NetworkResourcePropertiesUnion} properties Describes properties * of a network resource. */ properties: NetworkResourcePropertiesUnion; } /** * @interface * An interface representing GatewayDestination. * Describes destination endpoint for routing traffic. * */ export interface GatewayDestination { /** * @member {string} applicationName Name of the service fabric Mesh * application. */ applicationName: string; /** * @member {string} serviceName service that contains the endpoint. */ serviceName: string; /** * @member {string} endpointName name of the endpoint in the service. */ endpointName: string; } /** * @interface * An interface representing TcpConfig. * Describes the tcp configuration for external connectivity for this network. * */ export interface TcpConfig { /** * @member {string} name tcp gateway config name. */ name: string; /** * @member {number} port Specifies the port at which the service endpoint * below needs to be exposed. */ port: number; /** * @member {GatewayDestination} destination Describes destination endpoint * for routing traffic. */ destination: GatewayDestination; } /** * @interface * An interface representing HttpRouteMatchPath. * Path to match for routing. * */ export interface HttpRouteMatchPath { /** * @member {string} value Uri path to match for request. */ value: string; /** * @member {string} [rewrite] replacement string for matched part of the Uri. */ rewrite?: string; } /** * @interface * An interface representing HttpRouteMatchHeader. * Describes header information for http route matching. * */ export interface HttpRouteMatchHeader { /** * @member {string} name Name of header to match in request. */ name: string; /** * @member {string} [value] Value of header to match in request. */ value?: string; /** * @member {HeaderMatchType} [type] how to match header value. Possible * values include: 'exact' */ type?: HeaderMatchType; } /** * @interface * An interface representing HttpRouteMatchRule. * Describes a rule for http route matching. * */ export interface HttpRouteMatchRule { /** * @member {HttpRouteMatchPath} path Path to match for routing. */ path: HttpRouteMatchPath; /** * @member {HttpRouteMatchHeader[]} [headers] headers and their values to * match in request. */ headers?: HttpRouteMatchHeader[]; } /** * @interface * An interface representing HttpRouteConfig. * Describes the hostname properties for http routing. * */ export interface HttpRouteConfig { /** * @member {string} name http route name. */ name: string; /** * @member {HttpRouteMatchRule} match Describes a rule for http route * matching. */ match: HttpRouteMatchRule; /** * @member {GatewayDestination} destination Describes destination endpoint * for routing traffic. */ destination: GatewayDestination; } /** * @interface * An interface representing HttpHostConfig. * Describes the hostname properties for http routing. * */ export interface HttpHostConfig { /** * @member {string} name http hostname config name. */ name: string; /** * @member {HttpRouteConfig[]} routes Route information to use for routing. * Routes are processed in the order they are specified. Specify routes that * are more specific before routes that can hamdle general cases. */ routes: HttpRouteConfig[]; } /** * @interface * An interface representing HttpConfig. * Describes the http configuration for external connectivity for this network. * */ export interface HttpConfig { /** * @member {string} name http gateway config name. */ name: string; /** * @member {number} port Specifies the port at which the service endpoint * below needs to be exposed. */ port: number; /** * @member {HttpHostConfig[]} hosts description for routing. */ hosts: HttpHostConfig[]; } /** * @interface * An interface representing GatewayProperties. * Describes properties of a gateway resource. * */ export interface GatewayProperties { /** * @member {string} [description] User readable description of the gateway. */ description?: string; /** * @member {NetworkRef} sourceNetwork Network the gateway should listen on * for requests. */ sourceNetwork: NetworkRef; /** * @member {NetworkRef} destinationNetwork Network that the Application is * using. */ destinationNetwork: NetworkRef; /** * @member {TcpConfig[]} [tcp] Configuration for tcp connectivity for this * gateway. */ tcp?: TcpConfig[]; /** * @member {HttpConfig[]} [http] Configuration for http connectivity for this * gateway. */ http?: HttpConfig[]; /** * @member {ResourceStatus} [status] Status of the resource. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the gateway. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {string} [ipAddress] IP address of the gateway. This is populated * in the response and is ignored for incoming requests. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly ipAddress?: string; } /** * @interface * An interface representing GatewayResourceDescription. * This type describes a gateway resource. * * @extends TrackedResource */ export interface GatewayResourceDescription extends TrackedResource { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the gateway. */ description?: string; /** * @member {NetworkRef} sourceNetwork Network the gateway should listen on * for requests. */ sourceNetwork: NetworkRef; /** * @member {NetworkRef} destinationNetwork Network that the Application is * using. */ destinationNetwork: NetworkRef; /** * @member {TcpConfig[]} [tcp] Configuration for tcp connectivity for this * gateway. */ tcp?: TcpConfig[]; /** * @member {HttpConfig[]} [http] Configuration for http connectivity for this * gateway. */ http?: HttpConfig[]; /** * @member {ResourceStatus} [status] Status of the resource. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the gateway. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {string} [ipAddress] IP address of the gateway. This is populated * in the response and is ignored for incoming requests. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly ipAddress?: string; } /** * @interface * An interface representing ImageRegistryCredential. * Image registry credential. * */ export interface ImageRegistryCredential { /** * @member {string} server Docker image registry server, without protocol * such as `http` and `https`. */ server: string; /** * @member {string} username The username for the private registry. */ username: string; /** * @member {string} [password] The password for the private registry. The * password is required for create or update operations, however it is not * returned in the get or list operations. */ password?: string; } /** * @interface * An interface representing EnvironmentVariable. * Describes an environment variable for the container. * */ export interface EnvironmentVariable { /** * @member {string} [name] The name of the environment variable. */ name?: string; /** * @member {string} [value] The value of the environment variable. */ value?: string; } /** * @interface * An interface representing Setting. * Describes a setting for the container. The setting file path can be fetched * from environment variable "Fabric_SettingPath". The path for Windows * container is "C:\\secrets". The path for Linux container is "/var/secrets". * */ export interface Setting { /** * @member {string} [name] The name of the setting. */ name?: string; /** * @member {string} [value] The value of the setting. */ value?: string; } /** * @interface * An interface representing ContainerLabel. * Describes a container label. * */ export interface ContainerLabel { /** * @member {string} name The name of the container label. */ name: string; /** * @member {string} value The value of the container label. */ value: string; } /** * @interface * An interface representing EndpointProperties. * Describes a container endpoint. * */ export interface EndpointProperties { /** * @member {string} name The name of the endpoint. */ name: string; /** * @member {number} [port] Port used by the container. */ port?: number; } /** * @interface * An interface representing ResourceRequests. * This type describes the requested resources for a given container. It * describes the least amount of resources required for the container. A * container can consume more than requested resources up to the specified * limits before being restarted. Currently, the requested resources are * treated as limits. * */ export interface ResourceRequests { /** * @member {number} memoryInGB The memory request in GB for this container. */ memoryInGB: number; /** * @member {number} cpu Requested number of CPU cores. At present, only full * cores are supported. */ cpu: number; } /** * @interface * An interface representing ResourceLimits. * This type describes the resource limits for a given container. It describes * the most amount of resources a container is allowed to use before being * restarted. * */ export interface ResourceLimits { /** * @member {number} [memoryInGB] The memory limit in GB. */ memoryInGB?: number; /** * @member {number} [cpu] CPU limits in cores. At present, only full cores * are supported. */ cpu?: number; } /** * @interface * An interface representing ResourceRequirements. * This type describes the resource requirements for a container or a service. * */ export interface ResourceRequirements { /** * @member {ResourceRequests} requests Describes the requested resources for * a given container. */ requests: ResourceRequests; /** * @member {ResourceLimits} [limits] Describes the maximum limits on the * resources for a given container. */ limits?: ResourceLimits; } /** * @interface * An interface representing DiagnosticsRef. * Reference to sinks in DiagnosticsDescription. * */ export interface DiagnosticsRef { /** * @member {boolean} [enabled] Status of whether or not sinks are enabled. */ enabled?: boolean; /** * @member {string[]} [sinkRefs] List of sinks to be used if enabled. * References the list of sinks in DiagnosticsDescription. */ sinkRefs?: string[]; } /** * @interface * An interface representing ReliableCollectionsRef. * Specifying this parameter adds support for reliable collections * */ export interface ReliableCollectionsRef { /** * @member {string} name Name of ReliableCollection resource. Right now it's * not used and you can use any string. */ name: string; /** * @member {boolean} [doNotPersistState] False (the default) if * ReliableCollections state is persisted to disk as usual. True if you do * not want to persist state, in which case replication is still enabled and * you can use ReliableCollections as distributed cache. */ doNotPersistState?: boolean; } /** * @interface * An interface representing ContainerState. * The container state. * */ export interface ContainerState { /** * @member {string} [state] The state of this container */ state?: string; /** * @member {Date} [startTime] Date/time when the container state started. */ startTime?: Date; /** * @member {string} [exitCode] The container exit code. */ exitCode?: string; /** * @member {Date} [finishTime] Date/time when the container state finished. */ finishTime?: Date; /** * @member {string} [detailStatus] Human-readable status of this state. */ detailStatus?: string; } /** * @interface * An interface representing ContainerEvent. * A container event. * */ export interface ContainerEvent { /** * @member {string} [name] The name of the container event. */ name?: string; /** * @member {number} [count] The count of the event. */ count?: number; /** * @member {string} [firstTimestamp] Date/time of the first event. */ firstTimestamp?: string; /** * @member {string} [lastTimestamp] Date/time of the last event. */ lastTimestamp?: string; /** * @member {string} [message] The event message */ message?: string; /** * @member {string} [type] The event type. */ type?: string; } /** * @interface * An interface representing ContainerInstanceView. * Runtime information of a container instance. * */ export interface ContainerInstanceView { /** * @member {number} [restartCount] The number of times the container has been * restarted. */ restartCount?: number; /** * @member {ContainerState} [currentState] Current container instance state. */ currentState?: ContainerState; /** * @member {ContainerState} [previousState] Previous container instance * state. */ previousState?: ContainerState; /** * @member {ContainerEvent[]} [events] The events of this container instance. */ events?: ContainerEvent[]; } /** * @interface * An interface representing ContainerCodePackageProperties. * Describes a container and its runtime properties. * */ export interface ContainerCodePackageProperties { /** * @member {string} name The name of the code package. */ name: string; /** * @member {string} image The Container image to use. */ image: string; /** * @member {ImageRegistryCredential} [imageRegistryCredential] Image registry * credential. */ imageRegistryCredential?: ImageRegistryCredential; /** * @member {string} [entrypoint] Override for the default entry point in the * container. */ entrypoint?: string; /** * @member {string[]} [commands] Command array to execute within the * container in exec form. */ commands?: string[]; /** * @member {EnvironmentVariable[]} [environmentVariables] The environment * variables to set in this container */ environmentVariables?: EnvironmentVariable[]; /** * @member {Setting[]} [settings] The settings to set in this container. The * setting file path can be fetched from environment variable * "Fabric_SettingPath". The path for Windows container is "C:\\secrets". The * path for Linux container is "/var/secrets". */ settings?: Setting[]; /** * @member {ContainerLabel[]} [labels] The labels to set in this container. */ labels?: ContainerLabel[]; /** * @member {EndpointProperties[]} [endpoints] The endpoints exposed by this * container. */ endpoints?: EndpointProperties[]; /** * @member {ResourceRequirements} resources The resources required by this * container. */ resources: ResourceRequirements; /** * @member {VolumeReference[]} [volumeRefs] Volumes to be attached to the * container. The lifetime of these volumes is independent of the * application's lifetime. */ volumeRefs?: VolumeReference[]; /** * @member {ApplicationScopedVolume[]} [volumes] Volumes to be attached to * the container. The lifetime of these volumes is scoped to the * application's lifetime. */ volumes?: ApplicationScopedVolume[]; /** * @member {DiagnosticsRef} [diagnostics] Reference to sinks in * DiagnosticsDescription. */ diagnostics?: DiagnosticsRef; /** * @member {ReliableCollectionsRef[]} [reliableCollectionsRefs] A list of * ReliableCollection resources used by this particular code package. Please * refer to ReliablecollectionsRef for more details. */ reliableCollectionsRefs?: ReliableCollectionsRef[]; /** * @member {ContainerInstanceView} [instanceView] Runtime information of a * container instance. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly instanceView?: ContainerInstanceView; } /** * Contains the possible cases for AutoScalingTrigger. */ export type AutoScalingTriggerUnion = AutoScalingTrigger | AverageLoadScalingTrigger; /** * @interface * An interface representing AutoScalingTrigger. * Describes the trigger for performing auto scaling operation. * */ export interface AutoScalingTrigger { /** * @member {string} kind Polymorphic Discriminator */ kind: "AutoScalingTrigger"; } /** * Contains the possible cases for AutoScalingMechanism. */ export type AutoScalingMechanismUnion = AutoScalingMechanism | AddRemoveReplicaScalingMechanism; /** * @interface * An interface representing AutoScalingMechanism. * Describes the mechanism for performing auto scaling operation. Derived * classes will describe the actual mechanism. * */ export interface AutoScalingMechanism { /** * @member {string} kind Polymorphic Discriminator */ kind: "AutoScalingMechanism"; } /** * @interface * An interface representing AutoScalingPolicy. * Describes the auto scaling policy * */ export interface AutoScalingPolicy { /** * @member {string} name The name of the auto scaling policy. */ name: string; /** * @member {AutoScalingTriggerUnion} trigger Determines when auto scaling * operation will be invoked. */ trigger: AutoScalingTriggerUnion; /** * @member {AutoScalingMechanismUnion} mechanism The mechanism that is used * to scale when auto scaling operation is invoked. */ mechanism: AutoScalingMechanismUnion; } /** * @interface * An interface representing ServiceResourceDescription. * This type describes a service resource. * * @extends ManagedProxyResource */ export interface ServiceResourceDescription extends ManagedProxyResource { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {OperatingSystemType} osType The operation system required by the * code in service. Possible values include: 'Linux', 'Windows' */ osType: OperatingSystemType; /** * @member {ContainerCodePackageProperties[]} codePackages Describes the set * of code packages that forms the service. A code package describes the * container and the properties for running it. All the code packages are * started together on the same host and share the same context (network, * process etc.). */ codePackages: ContainerCodePackageProperties[]; /** * @member {NetworkRef[]} [networkRefs] The names of the private networks * that this service needs to be part of. */ networkRefs?: NetworkRef[]; /** * @member {DiagnosticsRef} [diagnostics] Reference to sinks in * DiagnosticsDescription. */ diagnostics?: DiagnosticsRef; /** * @member {string} [description] User readable description of the service. */ description?: string; /** * @member {number} [replicaCount] The number of replicas of the service to * create. Defaults to 1 if not specified. */ replicaCount?: number; /** * @member {AutoScalingPolicy[]} [autoScalingPolicies] Auto scaling policies */ autoScalingPolicies?: AutoScalingPolicy[]; /** * @member {ResourceStatus} [status] Status of the service. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {HealthState} [healthState] Describes the health state of an * application resource. Possible values include: 'Invalid', 'Ok', 'Warning', * 'Error', 'Unknown' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly healthState?: HealthState; /** * @member {string} [unhealthyEvaluation] When the service's health state is * not 'Ok', this additional details from service fabric Health Manager for * the user to know why the service is marked unhealthy. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unhealthyEvaluation?: string; } /** * Contains the possible cases for DiagnosticsSinkProperties. */ export type DiagnosticsSinkPropertiesUnion = DiagnosticsSinkProperties | AzureInternalMonitoringPipelineSinkDescription; /** * @interface * An interface representing DiagnosticsSinkProperties. * Properties of a DiagnosticsSink. * */ export interface DiagnosticsSinkProperties { /** * @member {string} kind Polymorphic Discriminator */ kind: "DiagnosticsSinkProperties"; /** * @member {string} [name] Name of the sink. This value is referenced by * DiagnosticsReferenceDescription */ name?: string; /** * @member {string} [description] A description of the sink. */ description?: string; } /** * @interface * An interface representing DiagnosticsDescription. * Describes the diagnostics options available * */ export interface DiagnosticsDescription { /** * @member {DiagnosticsSinkPropertiesUnion[]} [sinks] List of supported sinks * that can be referenced. */ sinks?: DiagnosticsSinkPropertiesUnion[]; /** * @member {boolean} [enabled] Status of whether or not sinks are enabled. */ enabled?: boolean; /** * @member {string[]} [defaultSinkRefs] The sinks to be used if diagnostics * is enabled. Sink choices can be overridden at the service and code package * level. */ defaultSinkRefs?: string[]; } /** * @interface * An interface representing ApplicationProperties. * Describes properties of a application resource. * */ export interface ApplicationProperties { /** * @member {string} [description] User readable description of the * application. */ description?: string; /** * @member {ServiceResourceDescription[]} [services] Describes the services * in the application. This property is used to create or modify services of * the application. On get only the name of the service is returned. The * service description can be obtained by querying for the service resource. */ services?: ServiceResourceDescription[]; /** * @member {DiagnosticsDescription} [diagnostics] Describes the diagnostics * definition and usage for an application resource. */ diagnostics?: DiagnosticsDescription; /** * @member {string} [debugParams] Internal - used by Visual Studio to setup * the debugging session on the local development environment. */ debugParams?: string; /** * @member {string[]} [serviceNames] Names of the services in the * application. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly serviceNames?: string[]; /** * @member {ResourceStatus} [status] Status of the application. Possible * values include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', * 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the application. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {HealthState} [healthState] Describes the health state of an * application resource. Possible values include: 'Invalid', 'Ok', 'Warning', * 'Error', 'Unknown' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly healthState?: HealthState; /** * @member {string} [unhealthyEvaluation] When the application's health state * is not 'Ok', this additional details from service fabric Health Manager * for the user to know why the application is marked unhealthy. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unhealthyEvaluation?: string; } /** * @interface * An interface representing AzureInternalMonitoringPipelineSinkDescription. * Diagnostics settings for Geneva. * */ export interface AzureInternalMonitoringPipelineSinkDescription { /** * @member {string} kind Polymorphic Discriminator */ kind: "AzureInternalMonitoringPipeline"; /** * @member {string} [name] Name of the sink. This value is referenced by * DiagnosticsReferenceDescription */ name?: string; /** * @member {string} [description] A description of the sink. */ description?: string; /** * @member {string} [accountName] Azure Internal monitoring pipeline account. */ accountName?: string; /** * @member {string} [namespace] Azure Internal monitoring pipeline account * namespace. */ namespace?: string; /** * @member {string} [maConfigUrl] Azure Internal monitoring agent * configuration. */ maConfigUrl?: string; /** * @member {any} [fluentdConfigUrl] Azure Internal monitoring agent fluentd * configuration. */ fluentdConfigUrl?: any; /** * @member {string} [autoKeyConfigUrl] Azure Internal monitoring pipeline * autokey associated with the certificate. */ autoKeyConfigUrl?: string; } /** * @interface * An interface representing ApplicationResourceDescription. * This type describes an application resource. * * @extends TrackedResource */ export interface ApplicationResourceDescription extends TrackedResource { /** * @member {string} [provisioningState] State of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: string; /** * @member {string} [description] User readable description of the * application. */ description?: string; /** * @member {ServiceResourceDescription[]} [services] Describes the services * in the application. This property is used to create or modify services of * the application. On get only the name of the service is returned. The * service description can be obtained by querying for the service resource. */ services?: ServiceResourceDescription[]; /** * @member {DiagnosticsDescription} [diagnostics] Describes the diagnostics * definition and usage for an application resource. */ diagnostics?: DiagnosticsDescription; /** * @member {string} [debugParams] Internal - used by Visual Studio to setup * the debugging session on the local development environment. */ debugParams?: string; /** * @member {string[]} [serviceNames] Names of the services in the * application. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly serviceNames?: string[]; /** * @member {ResourceStatus} [status] Status of the application. Possible * values include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', * 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the application. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {HealthState} [healthState] Describes the health state of an * application resource. Possible values include: 'Invalid', 'Ok', 'Warning', * 'Error', 'Unknown' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly healthState?: HealthState; /** * @member {string} [unhealthyEvaluation] When the application's health state * is not 'Ok', this additional details from service fabric Health Manager * for the user to know why the application is marked unhealthy. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unhealthyEvaluation?: string; } /** * @interface * An interface representing AddRemoveReplicaScalingMechanism. * Describes the horizontal auto scaling mechanism that adds or removes * replicas (containers or container groups). * */ export interface AddRemoveReplicaScalingMechanism { /** * @member {string} kind Polymorphic Discriminator */ kind: "AddRemoveReplica"; /** * @member {number} minCount Minimum number of containers (scale down won't * be performed below this number). */ minCount: number; /** * @member {number} maxCount Maximum number of containers (scale up won't be * performed above this number). */ maxCount: number; /** * @member {number} scaleIncrement Each time auto scaling is performed, this * number of containers will be added or removed. */ scaleIncrement: number; } /** * Contains the possible cases for AutoScalingMetric. */ export type AutoScalingMetricUnion = AutoScalingMetric | AutoScalingResourceMetric; /** * @interface * An interface representing AutoScalingMetric. * Describes the metric that is used for triggering auto scaling operation. * Derived classes will describe resources or metrics. * */ export interface AutoScalingMetric { /** * @member {string} kind Polymorphic Discriminator */ kind: "AutoScalingMetric"; } /** * @interface * An interface representing AutoScalingResourceMetric. * Describes the resource that is used for triggering auto scaling. * */ export interface AutoScalingResourceMetric { /** * @member {string} kind Polymorphic Discriminator */ kind: "Resource"; /** * @member {AutoScalingResourceMetricName} name Name of the resource. * Possible values include: 'cpu', 'memoryInGB' */ name: AutoScalingResourceMetricName; } /** * @interface * An interface representing ServiceProperties. * Describes properties of a service resource. * */ export interface ServiceProperties { /** * @member {string} [description] User readable description of the service. */ description?: string; /** * @member {number} [replicaCount] The number of replicas of the service to * create. Defaults to 1 if not specified. */ replicaCount?: number; /** * @member {AutoScalingPolicy[]} [autoScalingPolicies] Auto scaling policies */ autoScalingPolicies?: AutoScalingPolicy[]; /** * @member {ResourceStatus} [status] Status of the service. Possible values * include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly status?: ResourceStatus; /** * @member {string} [statusDetails] Gives additional information about the * current status of the service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly statusDetails?: string; /** * @member {HealthState} [healthState] Describes the health state of an * application resource. Possible values include: 'Invalid', 'Ok', 'Warning', * 'Error', 'Unknown' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly healthState?: HealthState; /** * @member {string} [unhealthyEvaluation] When the service's health state is * not 'Ok', this additional details from service fabric Health Manager for * the user to know why the service is marked unhealthy. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unhealthyEvaluation?: string; } /** * @interface * An interface representing ServiceReplicaProperties. * Describes the properties of a service replica. * */ export interface ServiceReplicaProperties { /** * @member {OperatingSystemType} osType The operation system required by the * code in service. Possible values include: 'Linux', 'Windows' */ osType: OperatingSystemType; /** * @member {ContainerCodePackageProperties[]} codePackages Describes the set * of code packages that forms the service. A code package describes the * container and the properties for running it. All the code packages are * started together on the same host and share the same context (network, * process etc.). */ codePackages: ContainerCodePackageProperties[]; /** * @member {NetworkRef[]} [networkRefs] The names of the private networks * that this service needs to be part of. */ networkRefs?: NetworkRef[]; /** * @member {DiagnosticsRef} [diagnostics] Reference to sinks in * DiagnosticsDescription. */ diagnostics?: DiagnosticsRef; } /** * @interface * An interface representing ServiceReplicaDescription. * Describes a replica of a service resource. * * @extends ServiceReplicaProperties */ export interface ServiceReplicaDescription extends ServiceReplicaProperties { /** * @member {string} replicaName Name of the replica. */ replicaName: string; } /** * @interface * An interface representing AverageLoadScalingTrigger. * Describes the average load trigger used for auto scaling. * */ export interface AverageLoadScalingTrigger { /** * @member {string} kind Polymorphic Discriminator */ kind: "AverageLoad"; /** * @member {AutoScalingMetricUnion} metric Description of the metric that is * used for scaling. */ metric: AutoScalingMetricUnion; /** * @member {number} lowerLoadThreshold Lower load threshold (if average load * is below this threshold, service will scale down). */ lowerLoadThreshold: number; /** * @member {number} upperLoadThreshold Upper load threshold (if average load * is above this threshold, service will scale up). */ upperLoadThreshold: number; /** * @member {number} scaleIntervalInSeconds Scale interval that indicates how * often will this trigger be checked. */ scaleIntervalInSeconds: number; } /** * @interface * An interface representing ContainerLogs. * Container logs. * */ export interface ContainerLogs { /** * @member {string} [content] Container logs. */ content?: string; } /** * @interface * An interface representing CodePackageGetContainerLogsOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface CodePackageGetContainerLogsOptionalParams extends msRest.RequestOptionsBase { /** * @member {number} [tail] Number of lines to show from the end of the logs. * Default is 100. */ tail?: number; } /** * @interface * An interface representing ServiceFabricMeshManagementClientOptions. * @extends AzureServiceClientOptions */ export interface ServiceFabricMeshManagementClientOptions extends AzureServiceClientOptions { /** * @member {string} [baseUri] */ baseUri?: string; } /** * @interface * An interface representing the OperationListResult. * Describes the result of the request to list Service Fabric operations. * * @extends Array<OperationResult> */ export interface OperationListResult extends Array<OperationResult> { /** * @member {string} [nextLink] URL to get the next set of operation list * results if there are any. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the SecretResourceDescriptionList. * A pageable list of secret resources. * * @extends Array<SecretResourceDescription> */ export interface SecretResourceDescriptionList extends Array<SecretResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the SecretValueResourceDescriptionList. * A pageable list of values of a secret resource. The information does not * include only the name of the value and not the actual unecrypted value. * * @extends Array<SecretValueResourceDescription> */ export interface SecretValueResourceDescriptionList extends Array<SecretValueResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the VolumeResourceDescriptionList. * A pageable list of volume resources. * * @extends Array<VolumeResourceDescription> */ export interface VolumeResourceDescriptionList extends Array<VolumeResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the NetworkResourceDescriptionList. * A pageable list of network resources. * * @extends Array<NetworkResourceDescription> */ export interface NetworkResourceDescriptionList extends Array<NetworkResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the GatewayResourceDescriptionList. * A pageable list of gateway resources. * * @extends Array<GatewayResourceDescription> */ export interface GatewayResourceDescriptionList extends Array<GatewayResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the ApplicationResourceDescriptionList. * A pageable list of application resources. * * @extends Array<ApplicationResourceDescription> */ export interface ApplicationResourceDescriptionList extends Array<ApplicationResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the ServiceResourceDescriptionList. * A pageable list of service resources. * * @extends Array<ServiceResourceDescription> */ export interface ServiceResourceDescriptionList extends Array<ServiceResourceDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * @interface * An interface representing the ServiceReplicaDescriptionList. * A pageable list of service replicas. * * @extends Array<ServiceReplicaDescription> */ export interface ServiceReplicaDescriptionList extends Array<ServiceReplicaDescription> { /** * @member {string} [nextLink] URI to fetch the next page of the list. */ nextLink?: string; } /** * Defines values for ResourceStatus. * Possible values include: 'Unknown', 'Ready', 'Upgrading', 'Creating', 'Deleting', 'Failed' * @readonly * @enum {string} */ export type ResourceStatus = 'Unknown' | 'Ready' | 'Upgrading' | 'Creating' | 'Deleting' | 'Failed'; /** * Defines values for HealthState. * Possible values include: 'Invalid', 'Ok', 'Warning', 'Error', 'Unknown' * @readonly * @enum {string} */ export type HealthState = 'Invalid' | 'Ok' | 'Warning' | 'Error' | 'Unknown'; /** * Defines values for SecretKind. * Possible values include: 'inlinedValue' * @readonly * @enum {string} */ export type SecretKind = 'inlinedValue'; /** * Defines values for VolumeProvider. * Possible values include: 'SFAzureFile' * @readonly * @enum {string} */ export type VolumeProvider = 'SFAzureFile'; /** * Defines values for SizeTypes. * Possible values include: 'Small', 'Medium', 'Large' * @readonly * @enum {string} */ export type SizeTypes = 'Small' | 'Medium' | 'Large'; /** * Defines values for ApplicationScopedVolumeKind. * Possible values include: 'ServiceFabricVolumeDisk' * @readonly * @enum {string} */ export type ApplicationScopedVolumeKind = 'ServiceFabricVolumeDisk'; /** * Defines values for NetworkKind. * Possible values include: 'Local' * @readonly * @enum {string} */ export type NetworkKind = 'Local'; /** * Defines values for HeaderMatchType. * Possible values include: 'exact' * @readonly * @enum {string} */ export type HeaderMatchType = 'exact'; /** * Defines values for OperatingSystemType. * Possible values include: 'Linux', 'Windows' * @readonly * @enum {string} */ export type OperatingSystemType = 'Linux' | 'Windows'; /** * Defines values for DiagnosticsSinkKind. * Possible values include: 'Invalid', 'AzureInternalMonitoringPipeline' * @readonly * @enum {string} */ export type DiagnosticsSinkKind = 'Invalid' | 'AzureInternalMonitoringPipeline'; /** * Defines values for AutoScalingMechanismKind. * Possible values include: 'AddRemoveReplica' * @readonly * @enum {string} */ export type AutoScalingMechanismKind = 'AddRemoveReplica'; /** * Defines values for AutoScalingMetricKind. * Possible values include: 'Resource' * @readonly * @enum {string} */ export type AutoScalingMetricKind = 'Resource'; /** * Defines values for AutoScalingResourceMetricName. * Possible values include: 'cpu', 'memoryInGB' * @readonly * @enum {string} */ export type AutoScalingResourceMetricName = 'cpu' | 'memoryInGB'; /** * Defines values for AutoScalingTriggerKind. * Possible values include: 'AverageLoad' * @readonly * @enum {string} */ export type AutoScalingTriggerKind = 'AverageLoad'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the create operation. */ export type SecretCreateResponse = SecretResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescription; }; }; /** * Contains response data for the get operation. */ export type SecretGetResponse = SecretResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescription; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type SecretListByResourceGroupResponse = SecretResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescriptionList; }; }; /** * Contains response data for the listBySubscription operation. */ export type SecretListBySubscriptionResponse = SecretResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescriptionList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type SecretListByResourceGroupNextResponse = SecretResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescriptionList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type SecretListBySubscriptionNextResponse = SecretResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretResourceDescriptionList; }; }; /** * Contains response data for the create operation. */ export type SecretValueCreateResponse = SecretValueResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretValueResourceDescription; }; }; /** * Contains response data for the get operation. */ export type SecretValueGetResponse = SecretValueResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretValueResourceDescription; }; }; /** * Contains response data for the list operation. */ export type SecretValueListResponse = SecretValueResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretValueResourceDescriptionList; }; }; /** * Contains response data for the listValue operation. */ export type SecretValueListValueResponse = SecretValue & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretValue; }; }; /** * Contains response data for the listNext operation. */ export type SecretValueListNextResponse = SecretValueResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SecretValueResourceDescriptionList; }; }; /** * Contains response data for the create operation. */ export type VolumeCreateResponse = VolumeResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescription; }; }; /** * Contains response data for the get operation. */ export type VolumeGetResponse = VolumeResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescription; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type VolumeListByResourceGroupResponse = VolumeResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescriptionList; }; }; /** * Contains response data for the listBySubscription operation. */ export type VolumeListBySubscriptionResponse = VolumeResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescriptionList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type VolumeListByResourceGroupNextResponse = VolumeResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescriptionList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type VolumeListBySubscriptionNextResponse = VolumeResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VolumeResourceDescriptionList; }; }; /** * Contains response data for the create operation. */ export type NetworkCreateResponse = NetworkResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescription; }; }; /** * Contains response data for the get operation. */ export type NetworkGetResponse = NetworkResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescription; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type NetworkListByResourceGroupResponse = NetworkResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescriptionList; }; }; /** * Contains response data for the listBySubscription operation. */ export type NetworkListBySubscriptionResponse = NetworkResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescriptionList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type NetworkListByResourceGroupNextResponse = NetworkResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescriptionList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type NetworkListBySubscriptionNextResponse = NetworkResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NetworkResourceDescriptionList; }; }; /** * Contains response data for the create operation. */ export type GatewayCreateResponse = GatewayResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescription; }; }; /** * Contains response data for the get operation. */ export type GatewayGetResponse = GatewayResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescription; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type GatewayListByResourceGroupResponse = GatewayResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescriptionList; }; }; /** * Contains response data for the listBySubscription operation. */ export type GatewayListBySubscriptionResponse = GatewayResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescriptionList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type GatewayListByResourceGroupNextResponse = GatewayResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescriptionList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type GatewayListBySubscriptionNextResponse = GatewayResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GatewayResourceDescriptionList; }; }; /** * Contains response data for the create operation. */ export type ApplicationCreateResponse = ApplicationResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescription; }; }; /** * Contains response data for the get operation. */ export type ApplicationGetResponse = ApplicationResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescription; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type ApplicationListByResourceGroupResponse = ApplicationResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescriptionList; }; }; /** * Contains response data for the listBySubscription operation. */ export type ApplicationListBySubscriptionResponse = ApplicationResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescriptionList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type ApplicationListByResourceGroupNextResponse = ApplicationResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescriptionList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type ApplicationListBySubscriptionNextResponse = ApplicationResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ApplicationResourceDescriptionList; }; }; /** * Contains response data for the get operation. */ export type ServiceGetResponse = ServiceResourceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResourceDescription; }; }; /** * Contains response data for the list operation. */ export type ServiceListResponse = ServiceResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResourceDescriptionList; }; }; /** * Contains response data for the listNext operation. */ export type ServiceListNextResponse = ServiceResourceDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResourceDescriptionList; }; }; /** * Contains response data for the get operation. */ export type ServiceReplicaGetResponse = ServiceReplicaDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceReplicaDescription; }; }; /** * Contains response data for the list operation. */ export type ServiceReplicaListResponse = ServiceReplicaDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceReplicaDescriptionList; }; }; /** * Contains response data for the listNext operation. */ export type ServiceReplicaListNextResponse = ServiceReplicaDescriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceReplicaDescriptionList; }; }; /** * Contains response data for the getContainerLogs operation. */ export type CodePackageGetContainerLogsResponse = ContainerLogs & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ContainerLogs; }; };
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormConnection_Information { interface Header extends DevKit.Controls.IHeader { /** Unique identifier of the source record. */ Record1Id: DevKit.Controls.Lookup; } interface tab_details_Sections { connect_from: DevKit.Controls.Section; details: DevKit.Controls.Section; } interface tab_info_Sections { description: DevKit.Controls.Section; info_s: DevKit.Controls.Section; } interface tab_details extends DevKit.Controls.ITab { Section: tab_details_Sections; } interface tab_info extends DevKit.Controls.ITab { Section: tab_info_Sections; } interface Tabs { details: tab_details; info: tab_info; } interface Body { Tab: Tabs; /** Type additional information to describe the connection, such as the length or quality of the relationship. */ Description: DevKit.Controls.String; /** Enter the end date of the connection. */ EffectiveEnd: DevKit.Controls.Date; /** Enter the start date of the connection. */ EffectiveStart: DevKit.Controls.Date; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the source record. */ Record1Id: DevKit.Controls.Lookup; /** Choose the primary party's role or relationship with the second party. */ Record1RoleId: DevKit.Controls.Lookup; /** Unique identifier of the target record. */ Record2Id: DevKit.Controls.Lookup; /** Choose the secondary party's role or relationship with the primary party. */ Record2RoleId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Shows whether the connection is active or inactive. Inactive connections are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.Controls.OptionSet; } } class FormConnection_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Connection_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Connection_Information */ Body: DevKit.FormConnection_Information.Body; /** The Footer section of form Connection_Information */ Footer: DevKit.FormConnection_Information.Footer; /** The Header section of form Connection_Information */ Header: DevKit.FormConnection_Information.Header; } class ConnectionApi { /** * DynamicsCrm.DevKit ConnectionApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the connection. */ ConnectionId: DevKit.WebApi.GuidValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type additional information to describe the connection, such as the length or quality of the relationship. */ Description: DevKit.WebApi.StringValue; /** Enter the end date of the connection. */ EffectiveEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the start date of the connection. */ EffectiveStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** The default image for the entity. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Indicates that this is the master record. */ IsMaster: DevKit.WebApi.BooleanValueReadonly; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the connection. */ Name: DevKit.WebApi.StringValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the connection. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the connection. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the source record. */ record1id_account: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_activitypointer: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_campaign: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_campaignactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ profileruleid1: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_competitor: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_constraintbasedgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_contract: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_email: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_entitlement: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_entitlementchannel: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_entitlementtemplatechannel: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_equipment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_incident: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_invoice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_lead: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_list: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreement: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_approval: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_bookingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_customerasset: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_inventoryjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_iotalert: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_iotdevice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_liveconversation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_payment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_paymentdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_paymentmethod: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_paymentterm: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_postalbum: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_postalcode: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_processnotes: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_productinventory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_project: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_projectteam: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_quotebookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_resourceterritory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rma: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rmaproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rmasubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rtv: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rtvproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_shipvia: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_taxcode: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_timegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_timeoffrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_warehouse: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorder: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msfp_alert: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_msfp_surveyresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_opportunity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_position: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_pricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_processsession: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_product: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_quote: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_resourcegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_salesorder: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_socialprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_systemuser: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_task: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_team: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_territory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ record1id_uii_option: DevKit.WebApi.LookupValue; /** Shows the record type of the source record. */ Record1ObjectTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Choose the primary party's role or relationship with the second party. */ Record1RoleId: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_account: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_activitypointer: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_campaign: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_campaignactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_competitor: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_constraintbasedgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_contract: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_email: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_entitlement: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_entitlementchannel: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_entitlementtemplatechannel: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_equipment: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_incident: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_invoice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_lead: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_list: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreement: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_approval: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_bookingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_customerasset: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_inventoryjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_iotalert: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_iotdevice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_liveconversation: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_payment: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_paymentdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_paymentmethod: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_paymentterm: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_postalbum: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_postalcode: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_processnotes: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_productinventory: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_project: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_projectteam: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_quotebookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_resourceterritory: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rma: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rmaproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rmasubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rtv: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rtvproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_shipvia: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_taxcode: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_timegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_timeoffrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_warehouse: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorder: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msfp_alert: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_msfp_surveyresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_opportunity: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_position: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_pricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_processsession: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_product: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_quote: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_resourcegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_salesorder: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_socialprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_systemuser: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_task: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_team: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_territory: DevKit.WebApi.LookupValue; /** Unique identifier of the target record. */ record2id_uii_option: DevKit.WebApi.LookupValue; /** Shows the record type of the target record. */ Record2ObjectTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Choose the secondary party's role or relationship with the primary party. */ Record2RoleId: DevKit.WebApi.LookupValue; /** Unique identifier for the reciprocal connection record. */ RelatedConnectionId: DevKit.WebApi.LookupValueReadonly; /** Shows whether the connection is active or inactive. Inactive connections are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the connection. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Version number of the connection. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Connection { enum Record1ObjectTypeCode { /** 1 */ Account, /** 4200 */ Activity, /** 10413 */ Agreement, /** 10414 */ Agreement_Booking_Date, /** 10415 */ Agreement_Booking_Incident, /** 10416 */ Agreement_Booking_Product, /** 10417 */ Agreement_Booking_Service, /** 10418 */ Agreement_Booking_Service_Task, /** 10419 */ Agreement_Booking_Setup, /** 10420 */ Agreement_Invoice_Date, /** 10421 */ Agreement_Invoice_Product, /** 10422 */ Agreement_Invoice_Setup, /** 4201 */ Appointment, /** 10294 */ Booking_Alert, /** 10295 */ Booking_Alert_Status, /** 10297 */ Booking_Rule, /** 10425 */ Booking_Timestamp, /** 4400 */ Campaign, /** 4402 */ Campaign_Activity, /** 112 */ Case, /** 9400 */ Channel_Access_Profile_Rule, /** 123 */ Competitor, /** 2 */ Contact, /** 1010 */ Contract, /** 10564 */ Conversation, /** 10116 */ Customer_Asset, /** 10238 */ Customer_Voice_alert, /** 10248 */ Customer_Voice_survey_invite, /** 10250 */ Customer_Voice_survey_response, /** 4202 */ Email, /** 9700 */ Entitlement, /** 9701 */ Entitlement_Channel, /** 9703 */ Entitlement_Template_Channel, /** 4000 */ FacilityEquipment, /** 4204 */ Fax, /** 10317 */ Fulfillment_Preference, /** 9600 */ Goal, /** 10436 */ Incident_Type_Characteristic, /** 10437 */ Incident_Type_Product, /** 10438 */ Incident_Type_Service, /** 10442 */ Inventory_Adjustment, /** 10443 */ Inventory_Adjustment_Product, /** 10444 */ Inventory_Journal, /** 10445 */ Inventory_Transfer, /** 1090 */ Invoice, /** 10126 */ IoT_Alert, /** 10127 */ IoT_Device, /** 10128 */ IoT_Device_Category, /** 10129 */ IoT_Device_Command, /** 10133 */ IoT_Device_Registration_History, /** 9953 */ Knowledge_Article, /** 9930 */ Knowledge_Base_Record, /** 4 */ Lead, /** 4207 */ Letter, /** 4300 */ Marketing_List, /** 10558 */ Ongoing_conversation_Deprecated, /** 3 */ Opportunity, /** 10679 */ Option, /** 1088 */ Order, /** 10673 */ Outbound_message, /** 10450 */ Payment, /** 10451 */ Payment_Detail, /** 10452 */ Payment_Method, /** 10453 */ Payment_Term, /** 4210 */ Phone_Call, /** 50 */ Position, /** 10454 */ Postal_Code, /** 1022 */ Price_List, /** 10362 */ Process_Notes, /** 4710 */ Process_Session, /** 1024 */ Product, /** 10455 */ Product_Inventory, /** 10233 */ Profile_Album, /** 10363 */ Project, /** 10324 */ Project_Service_Approval, /** 10371 */ Project_Team_Member, /** 10456 */ Purchase_Order, /** 10457 */ Purchase_Order_Bill, /** 10458 */ Purchase_Order_Product, /** 10459 */ Purchase_Order_Receipt, /** 10460 */ Purchase_Order_Receipt_Product, /** 10461 */ Purchase_Order_SubStatus, /** 1084 */ Quote, /** 10462 */ Quote_Booking_Incident, /** 10463 */ Quote_Booking_Product, /** 10464 */ Quote_Booking_Service, /** 10465 */ Quote_Booking_Service_Task, /** 4251 */ Recurring_Appointment, /** 4007 */ Resource_Group, /** 10490 */ Resource_Restriction_Deprecated, /** 10313 */ Resource_Territory, /** 10470 */ RMA, /** 10471 */ RMA_Product, /** 10472 */ RMA_Receipt, /** 10473 */ RMA_Receipt_Product, /** 10474 */ RMA_SubStatus, /** 10475 */ RTV, /** 10476 */ RTV_Product, /** 10477 */ RTV_Substatus, /** 4005 */ Scheduling_Group, /** 4214 */ Service_Activity, /** 10573 */ Session, /** 10479 */ Ship_Via, /** 4216 */ Social_Activity, /** 99 */ Social_Profile, /** 10316 */ System_User_Scheduler_Setting, /** 4212 */ Task, /** 10480 */ Tax_Code, /** 9 */ Team, /** 2013 */ Territory, /** 10318 */ Time_Group_Detail, /** 10482 */ Time_Off_Request, /** 10702 */ Toolbar_Button, /** 8 */ User, /** 10484 */ Warehouse, /** 10485 */ Work_Order, /** 10486 */ Work_Order_Characteristic_Deprecated, /** 10488 */ Work_Order_Incident, /** 10489 */ Work_Order_Product, /** 10491 */ Work_Order_Service, /** 10492 */ Work_Order_Service_Task } enum Record2ObjectTypeCode { /** 1 */ Account, /** 4200 */ Activity, /** 10413 */ Agreement, /** 10414 */ Agreement_Booking_Date, /** 10415 */ Agreement_Booking_Incident, /** 10416 */ Agreement_Booking_Product, /** 10417 */ Agreement_Booking_Service, /** 10418 */ Agreement_Booking_Service_Task, /** 10419 */ Agreement_Booking_Setup, /** 10420 */ Agreement_Invoice_Date, /** 10421 */ Agreement_Invoice_Product, /** 10422 */ Agreement_Invoice_Setup, /** 4201 */ Appointment, /** 10294 */ Booking_Alert, /** 10295 */ Booking_Alert_Status, /** 10297 */ Booking_Rule, /** 10425 */ Booking_Timestamp, /** 4400 */ Campaign, /** 4402 */ Campaign_Activity, /** 112 */ Case, /** 9400 */ Channel_Access_Profile_Rule, /** 123 */ Competitor, /** 2 */ Contact, /** 1010 */ Contract, /** 10564 */ Conversation, /** 10116 */ Customer_Asset, /** 10238 */ Customer_Voice_alert, /** 10248 */ Customer_Voice_survey_invite, /** 10250 */ Customer_Voice_survey_response, /** 4202 */ Email, /** 9700 */ Entitlement, /** 9701 */ Entitlement_Channel, /** 9703 */ Entitlement_Template_Channel, /** 4000 */ FacilityEquipment, /** 4204 */ Fax, /** 10317 */ Fulfillment_Preference, /** 9600 */ Goal, /** 10436 */ Incident_Type_Characteristic, /** 10437 */ Incident_Type_Product, /** 10438 */ Incident_Type_Service, /** 10442 */ Inventory_Adjustment, /** 10443 */ Inventory_Adjustment_Product, /** 10444 */ Inventory_Journal, /** 10445 */ Inventory_Transfer, /** 1090 */ Invoice, /** 10126 */ IoT_Alert, /** 10127 */ IoT_Device, /** 10128 */ IoT_Device_Category, /** 10129 */ IoT_Device_Command, /** 10133 */ IoT_Device_Registration_History, /** 9953 */ Knowledge_Article, /** 9930 */ Knowledge_Base_Record, /** 4 */ Lead, /** 4207 */ Letter, /** 4300 */ Marketing_List, /** 10558 */ Ongoing_conversation_Deprecated, /** 3 */ Opportunity, /** 10679 */ Option, /** 1088 */ Order, /** 10673 */ Outbound_message, /** 10450 */ Payment, /** 10451 */ Payment_Detail, /** 10452 */ Payment_Method, /** 10453 */ Payment_Term, /** 4210 */ Phone_Call, /** 50 */ Position, /** 10454 */ Postal_Code, /** 1022 */ Price_List, /** 10362 */ Process_Notes, /** 4710 */ Process_Session, /** 1024 */ Product, /** 10455 */ Product_Inventory, /** 10233 */ Profile_Album, /** 10363 */ Project, /** 10324 */ Project_Service_Approval, /** 10371 */ Project_Team_Member, /** 10456 */ Purchase_Order, /** 10457 */ Purchase_Order_Bill, /** 10458 */ Purchase_Order_Product, /** 10459 */ Purchase_Order_Receipt, /** 10460 */ Purchase_Order_Receipt_Product, /** 10461 */ Purchase_Order_SubStatus, /** 1084 */ Quote, /** 10462 */ Quote_Booking_Incident, /** 10463 */ Quote_Booking_Product, /** 10464 */ Quote_Booking_Service, /** 10465 */ Quote_Booking_Service_Task, /** 4251 */ Recurring_Appointment, /** 4007 */ Resource_Group, /** 10490 */ Resource_Restriction_Deprecated, /** 10313 */ Resource_Territory, /** 10470 */ RMA, /** 10471 */ RMA_Product, /** 10472 */ RMA_Receipt, /** 10473 */ RMA_Receipt_Product, /** 10474 */ RMA_SubStatus, /** 10475 */ RTV, /** 10476 */ RTV_Product, /** 10477 */ RTV_Substatus, /** 4005 */ Scheduling_Group, /** 4214 */ Service_Activity, /** 10573 */ Session, /** 10479 */ Ship_Via, /** 4216 */ Social_Activity, /** 99 */ Social_Profile, /** 10316 */ System_User_Scheduler_Setting, /** 4212 */ Task, /** 10480 */ Tax_Code, /** 9 */ Team, /** 2013 */ Territory, /** 10318 */ Time_Group_Detail, /** 10482 */ Time_Off_Request, /** 10702 */ Toolbar_Button, /** 8 */ User, /** 10484 */ Warehouse, /** 10485 */ Work_Order, /** 10486 */ Work_Order_Characteristic_Deprecated, /** 10488 */ Work_Order_Incident, /** 10489 */ Work_Order_Product, /** 10491 */ Work_Order_Service, /** 10492 */ Work_Order_Service_Task } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { PivotCommon } from '../base/pivot-common'; import * as events from '../../common/base/constant'; import { IFieldOptions, IField } from '../../base/engine'; import { SummaryTypes } from '../../base/types'; import { FieldDroppedEventArgs, FieldDropEventArgs } from '../base/interface'; import { OlapEngine, IOlapField } from '../../base/olap/engine'; import { PivotButton } from '../actions/pivot-button'; import { PivotUtil } from '../../base/util'; import { PivotView } from '../../pivotview/base/pivotview'; import { PivotFieldList } from '../../pivotfieldlist/base/field-list'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; /** * `DataSourceUpdate` module is used to update the dataSource. */ /** @hidden */ export class DataSourceUpdate { public parent: PivotCommon; /** @hidden */ public btnElement: HTMLElement; /** @hidden */ /* eslint-disable-next-line */ public control: any; /** @hidden */ public pivotButton: PivotButton; /** * Constructor for the dialog action. * @param {PivotCommon} parent - parent. * @hidden */ constructor(parent?: PivotCommon) { /* eslint-disable-line */ this.parent = parent; } /** * Updates the dataSource by adding the given field along with field dropped position to the dataSource. * @function updateDataSource * @param {string} fieldName - Defines dropped field name to update dataSource. * @param {string} droppedClass - Defines dropped field axis name to update dataSource. * @param {number} droppedPosition - Defines dropped position to the axis based on field position. * @returns {void} * @hidden */ public updateDataSource(fieldName: string, droppedClass: string, droppedPosition: number): void { let dataSourceItem: IFieldOptions; let draggedClass: string; let draggedPosition: number = -1; let row: IFieldOptions[] = this.parent.dataSourceSettings.rows; let column: IFieldOptions[] = this.parent.dataSourceSettings.columns; let value: IFieldOptions[] = this.parent.dataSourceSettings.values; let filter: IFieldOptions[] = this.parent.dataSourceSettings.filters; let field: IFieldOptions[][] = [row, column, value, filter]; for (let len: number = 0, lnt: number = field.length; len < lnt; len++) { if (field[len]) { for (let i: number = 0, n: number = field[len].length; i < n; i++) { if (field[len][i].name === fieldName || (this.parent.dataType === 'olap' && field[len][i].name.toLowerCase() === '[measures]' && field[len][i].name.toLowerCase() === fieldName)) { draggedClass = len === 0 ? 'rows' : len === 1 ? 'columns' : len === 2 ? 'values' : 'filters'; draggedPosition = i; } if (!draggedClass) { draggedClass = 'fieldList'; } } } } let eventdrop: FieldDropEventArgs = { fieldName: fieldName, dropField: PivotUtil.getFieldInfo(fieldName, this.control).fieldItem, dataSourceSettings: PivotUtil.getClonedDataSourceSettings(this.parent.dataSourceSettings), dropAxis: droppedClass, dropPosition: droppedPosition, draggedAxis: draggedClass, cancel: false }; let control: PivotView | PivotFieldList = this.control.getModuleName() === 'pivotfieldlist' && this.control.isPopupView ? this.control.pivotGridModule : this.control; control.trigger(events.fieldDrop, eventdrop, (observedArgs: FieldDropEventArgs) => { if (!observedArgs.cancel) { droppedClass = observedArgs.dropAxis; droppedPosition = observedArgs.dropPosition; fieldName = observedArgs.dropField ? observedArgs.dropField.name : observedArgs.fieldName; dataSourceItem = observedArgs.dropField; if (this.control && this.btnElement && this.btnElement.getAttribute('isvalue') === 'true') { switch (droppedClass) { case '': this.control.setProperties({ dataSourceSettings: { values: [] } }, true); break; case 'rows': droppedPosition = droppedPosition === this.parent.dataSourceSettings.rows.length ? -1 : droppedPosition; this.control.setProperties({ dataSourceSettings: { valueAxis: 'row', valueIndex: droppedPosition } }, true); break; case 'columns': droppedPosition = droppedPosition === this.parent.dataSourceSettings.columns.length ? -1 : droppedPosition; this.control.setProperties({ dataSourceSettings: { valueAxis: 'column', valueIndex: droppedPosition } }, true); break; } } else { // dataSourceItem = this.removeFieldFromReport(fieldName.toString()); // dataSourceItem = dataSourceItem ? dataSourceItem : this.getNewField(fieldName.toString()); this.removeFieldFromReport(fieldName.toString()); if (this.parent.dataType === 'pivot' && this.control.showValuesButton && this.parent.dataSourceSettings.values.length > 1) { let dropAxisFields: IFieldOptions[] = (this.parent.dataSourceSettings.valueAxis === 'row' && droppedClass === 'rows') ? this.parent.dataSourceSettings.rows : (this.parent.dataSourceSettings.valueAxis === 'column' && droppedClass === 'columns') ? this.parent.dataSourceSettings.columns : undefined; if (draggedPosition < this.parent.dataSourceSettings.valueIndex && ((this.parent.dataSourceSettings.valueAxis === 'row' && draggedClass === 'rows') || (this.parent.dataSourceSettings.valueAxis === 'column' && draggedClass === 'columns'))) { this.control.setProperties({ dataSourceSettings: { valueIndex: this.parent.dataSourceSettings.valueIndex - 1 } }, true); } if (!isNullOrUndefined(dropAxisFields)) { if (droppedPosition === -1 && this.parent.dataSourceSettings.valueIndex === -1) { this.control.setProperties({ dataSourceSettings: { valueIndex: dropAxisFields.length } }, true); } else if (droppedPosition > -1 && droppedPosition <= this.parent.dataSourceSettings.valueIndex) { this.control.setProperties({ dataSourceSettings: { valueIndex: this.parent.dataSourceSettings.valueIndex + 1 } }, true); } else if (this.parent.dataSourceSettings.valueIndex > -1 && droppedPosition > this.parent.dataSourceSettings.valueIndex) { droppedPosition = droppedPosition - 1; } } } dataSourceItem = this.getNewField(fieldName.toString(), observedArgs.dropField); if (dataSourceItem.type === 'CalculatedField' && droppedClass !== '') { droppedClass = 'values'; } } if (this.parent.dataType === 'olap') { // dataSourceItem = this.removeFieldFromReport(fieldName.toString()); // dataSourceItem = dataSourceItem ? dataSourceItem : this.getNewField(fieldName.toString()); this.removeFieldFromReport(fieldName.toString()); dataSourceItem = this.getNewField(fieldName.toString(), observedArgs.dropField); if (this.parent.dataSourceSettings.values.length === 0) { this.removeFieldFromReport('[measures]'); } if (dataSourceItem.type === 'CalculatedField' && droppedClass !== '') { droppedClass = 'values'; } } if (this.control) { let eventArgs: FieldDroppedEventArgs = { fieldName: fieldName, droppedField: dataSourceItem, dataSourceSettings: PivotUtil.getClonedDataSourceSettings(this.parent.dataSourceSettings), droppedAxis: droppedClass, droppedPosition: droppedPosition }; /* eslint-disable */ control.trigger(events.onFieldDropped, eventArgs, (droppedArgs: FieldDroppedEventArgs) => { dataSourceItem = droppedArgs.droppedField; if (dataSourceItem) { droppedPosition = droppedArgs.droppedPosition; droppedClass = droppedArgs.droppedAxis; switch (droppedClass) { case 'filters': droppedPosition !== -1 ? this.parent.dataSourceSettings.filters.splice(droppedPosition, 0, dataSourceItem) : this.parent.dataSourceSettings.filters.push(dataSourceItem); break; case 'rows': droppedPosition !== -1 ? this.parent.dataSourceSettings.rows.splice(droppedPosition, 0, dataSourceItem) : this.parent.dataSourceSettings.rows.push(dataSourceItem); break; case 'columns': droppedPosition !== -1 ? this.parent.dataSourceSettings.columns.splice(droppedPosition, 0, dataSourceItem) : this.parent.dataSourceSettings.columns.push(dataSourceItem); break; case 'values': droppedPosition !== -1 ? this.parent.dataSourceSettings.values.splice(droppedPosition, 0, dataSourceItem) : this.parent.dataSourceSettings.values.push(dataSourceItem); if (this.parent.dataType === 'olap' && !(this.parent.engineModule as OlapEngine).isMeasureAvail) { let measureField: IFieldOptions = { name: '[Measures]', caption: 'Measures', showRemoveIcon: true, allowDragAndDrop: true }; let fieldAxis: IFieldOptions[] = this.parent.dataSourceSettings.valueAxis === 'row' ? this.parent.dataSourceSettings.rows : this.parent.dataSourceSettings.columns; fieldAxis.push(measureField); } break; } } }); } } }); } /** * Updates the dataSource by removing the given field from the dataSource. * @param {string} fieldName - Defines dropped field name to remove dataSource. * @function removeFieldFromReport * @returns {void} * @hidden */ public removeFieldFromReport(fieldName: string): IFieldOptions { /* eslint-enable */ let dataSourceItem: IFieldOptions; let isDataSource: boolean = false; let rows: IFieldOptions[] = this.parent.dataSourceSettings.rows; let columns: IFieldOptions[] = this.parent.dataSourceSettings.columns; let values: IFieldOptions[] = this.parent.dataSourceSettings.values; let filters: IFieldOptions[] = this.parent.dataSourceSettings.filters; let fields: IFieldOptions[][] = [rows, columns, values, filters]; let field: IField = this.parent.engineModule.fieldList[fieldName]; for (let len: number = 0, lnt: number = fields.length; len < lnt; len++) { if (!isDataSource && fields[len]) { for (let i: number = 0, n: number = fields[len].length; i < n; i++) { if (fields[len][i].name === fieldName || (this.parent.dataType === 'olap' && fields[len][i].name.toLowerCase() === '[measures]' && fields[len][i].name.toLowerCase() === fieldName)) { dataSourceItem = (<{ [key: string]: IFieldOptions }>fields[len][i]).properties ? (<{ [key: string]: IFieldOptions }>fields[len][i]).properties : fields[len][i]; dataSourceItem.type = (field && field.type === 'number') ? dataSourceItem.type : 'Count' as SummaryTypes; fields[len].splice(i, 1); if (this.parent.dataType === 'olap') { let engineModule: OlapEngine = this.parent.engineModule as OlapEngine; if (engineModule && engineModule.fieldList[fieldName]) { engineModule.fieldList[fieldName].currrentMembers = {}; engineModule.fieldList[fieldName].searchMembers = []; } } isDataSource = true; break; } } } } return dataSourceItem; } /** * Creates new field object given field name from the field list data. * @param {string} fieldName - Defines dropped field name to add dataSource. * @param {IFieldOptions} fieldItem - Defines dropped field. * @function getNewField * @returns {IFieldOptions} - IFieldOptions * @hidden */ public getNewField(fieldName: string, fieldItem?: IFieldOptions): IFieldOptions { let newField: IFieldOptions; if (this.parent.dataType === 'olap') { let field: IOlapField = (this.parent.engineModule as OlapEngine).fieldList[fieldName]; newField = { name: fieldItem ? fieldItem.name : fieldName, caption: fieldItem ? fieldItem.caption : field.caption, isNamedSet: fieldItem ? fieldItem.isNamedSet : field.isNamedSets, isCalculatedField: fieldItem ? fieldItem.isCalculatedField : field.isCalculatedField, type: (fieldItem ? (fieldItem.type === undefined ? field.type === 'number' ? 'Sum' as SummaryTypes : 'Count' as SummaryTypes : fieldItem.type) : ((field.aggregateType as SummaryTypes) === undefined ? field.type === 'number' ? 'Sum' as SummaryTypes : 'Count' as SummaryTypes : field.aggregateType as SummaryTypes)), showFilterIcon: fieldItem ? fieldItem.showFilterIcon : field.showFilterIcon, showSortIcon: fieldItem ? fieldItem.showSortIcon : field.showSortIcon, showEditIcon: fieldItem ? fieldItem.showEditIcon : field.showEditIcon, showRemoveIcon: fieldItem ? fieldItem.showRemoveIcon : field.showRemoveIcon, showValueTypeIcon: fieldItem ? fieldItem.showValueTypeIcon : field.showValueTypeIcon, allowDragAndDrop: fieldItem ? fieldItem.allowDragAndDrop : field.allowDragAndDrop, showSubTotals: fieldItem ? fieldItem.showSubTotals : field.showSubTotals }; } else { let field: IField = this.parent.engineModule.fieldList[fieldName]; newField = { name: fieldItem ? fieldItem.name : fieldName, caption: fieldItem ? fieldItem.caption : field.caption, type: (fieldItem ? ((fieldItem.type === undefined || fieldItem.type === null) ? field.type === 'number' ? 'Sum' as SummaryTypes : 'Count' as SummaryTypes : fieldItem.type) : (((field.aggregateType as SummaryTypes) === undefined || (field.aggregateType as SummaryTypes) === null) ? field.type === 'number' ? 'Sum' as SummaryTypes : 'Count' as SummaryTypes : field.aggregateType as SummaryTypes)), showNoDataItems: fieldItem ? fieldItem.showNoDataItems : field.showNoDataItems, baseField: fieldItem ? fieldItem.baseField : field.baseField, baseItem: fieldItem ? fieldItem.baseItem : field.baseItem, allowDragAndDrop: fieldItem ? fieldItem.allowDragAndDrop : field.allowDragAndDrop, showSubTotals: fieldItem ? fieldItem.showSubTotals : field.showSubTotals, showFilterIcon: fieldItem ? fieldItem.showFilterIcon : field.showFilterIcon, showSortIcon: fieldItem ? fieldItem.showSortIcon : field.showSortIcon, showEditIcon: fieldItem ? fieldItem.showEditIcon : field.showEditIcon, showRemoveIcon: fieldItem ? fieldItem.showRemoveIcon : field.showRemoveIcon, showValueTypeIcon: fieldItem ? fieldItem.showValueTypeIcon : field.showValueTypeIcon }; } return newField; } }
the_stack
'use strict'; import URI from 'vs/base/common/uri'; import winjs = require('vs/base/common/winjs.base'); import editorCommon = require('vs/editor/common/editorCommon'); import modes = require('vs/editor/common/modes'); import htmlWorker = require('vs/languages/html/common/htmlWorker'); import { CompatMode, createWordRegExp, ModeWorkerManager } from 'vs/editor/common/modes/abstractMode'; import { AbstractState } from 'vs/editor/common/modes/abstractState'; import {IModeService} from 'vs/editor/common/services/modeService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import * as htmlTokenTypes from 'vs/languages/html/common/htmlTokenTypes'; import {EMPTY_ELEMENTS} from 'vs/languages/html/common/htmlEmptyTagsShared'; import {LanguageConfigurationRegistry, LanguageConfiguration} from 'vs/editor/common/modes/languageConfigurationRegistry'; import {TokenizationSupport, IEnteringNestedModeData, ILeavingNestedModeData, ITokenizationCustomization} from 'vs/editor/common/modes/supports/tokenizationSupport'; import {wireCancellationToken} from 'vs/base/common/async'; import {ICompatWorkerService, CompatWorkerAttr} from 'vs/editor/common/services/compatWorkerService'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IHTMLConfiguration} from 'vs/languages/html/common/html.contribution'; export { htmlTokenTypes }; // export to be used by Razor. We are the main module, so Razor should get it from us. export { EMPTY_ELEMENTS }; // export to be used by Razor. We are the main module, so Razor should get it from us. export enum States { Content, OpeningStartTag, OpeningEndTag, WithinDoctype, WithinTag, WithinComment, WithinEmbeddedContent, AttributeName, AttributeValue } // list of elements that embed other content var tagsEmbeddingContent:string[] = ['script', 'style']; export class State extends AbstractState { public kind:States; public lastTagName:string; public lastAttributeName:string; public embeddedContentType:string; public attributeValueQuote:string; public attributeValueLength:number; constructor(mode:modes.IMode, kind:States, lastTagName:string, lastAttributeName:string, embeddedContentType:string, attributeValueQuote:string, attributeValueLength:number) { super(mode); this.kind = kind; this.lastTagName = lastTagName; this.lastAttributeName = lastAttributeName; this.embeddedContentType = embeddedContentType; this.attributeValueQuote = attributeValueQuote; this.attributeValueLength = attributeValueLength; } static escapeTagName(s:string):string { return htmlTokenTypes.getTag(s.replace(/[:_.]/g, '-')); } public makeClone():State { return new State(this.getMode(), this.kind, this.lastTagName, this.lastAttributeName, this.embeddedContentType, this.attributeValueQuote, this.attributeValueLength); } public equals(other:modes.IState):boolean { if (other instanceof State) { return ( super.equals(other) && this.kind === other.kind && this.lastTagName === other.lastTagName && this.lastAttributeName === other.lastAttributeName && this.embeddedContentType === other.embeddedContentType && this.attributeValueQuote === other.attributeValueQuote && this.attributeValueLength === other.attributeValueLength ); } return false; } private nextElementName(stream:modes.IStream):string { return stream.advanceIfRegExp(/^[_:\w][_:\w-.\d]*/).toLowerCase(); } private nextAttributeName(stream:modes.IStream):string { return stream.advanceIfRegExp(/^[^\s"'>/=\x00-\x0F\x7F\x80-\x9F]*/).toLowerCase(); } public tokenize(stream:modes.IStream) : modes.ITokenizationResult { switch(this.kind){ case States.WithinComment: if (stream.advanceUntilString2('-->', false)) { return { type: htmlTokenTypes.COMMENT}; } else if(stream.advanceIfString2('-->')) { this.kind = States.Content; return { type: htmlTokenTypes.DELIM_COMMENT, dontMergeWithPrev: true }; } break; case States.WithinDoctype: if (stream.advanceUntilString2('>', false)) { return { type: htmlTokenTypes.DOCTYPE}; } else if(stream.advanceIfString2('>')) { this.kind = States.Content; return { type: htmlTokenTypes.DELIM_DOCTYPE, dontMergeWithPrev: true }; } break; case States.Content: if (stream.advanceIfCharCode2('<'.charCodeAt(0))) { if (!stream.eos() && stream.peek() === '!') { if (stream.advanceIfString2('!--')) { this.kind = States.WithinComment; return { type: htmlTokenTypes.DELIM_COMMENT, dontMergeWithPrev: true }; } if (stream.advanceIfStringCaseInsensitive2('!DOCTYPE')) { this.kind = States.WithinDoctype; return { type: htmlTokenTypes.DELIM_DOCTYPE, dontMergeWithPrev: true }; } } if (stream.advanceIfCharCode2('/'.charCodeAt(0))) { this.kind = States.OpeningEndTag; return { type: htmlTokenTypes.DELIM_END, dontMergeWithPrev: true }; } this.kind = States.OpeningStartTag; return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true }; } break; case States.OpeningEndTag: var tagName = this.nextElementName(stream); if (tagName.length > 0){ return { type: State.escapeTagName(tagName), }; } else if (stream.advanceIfString2('>')) { this.kind = States.Content; return { type: htmlTokenTypes.DELIM_END, dontMergeWithPrev: true }; } else { stream.advanceUntilString2('>', false); return { type: '' }; } case States.OpeningStartTag: this.lastTagName = this.nextElementName(stream); if (this.lastTagName.length > 0) { this.lastAttributeName = null; if ('script' === this.lastTagName || 'style' === this.lastTagName) { this.lastAttributeName = null; this.embeddedContentType = null; } this.kind = States.WithinTag; return { type: State.escapeTagName(this.lastTagName), }; } break; case States.WithinTag: if (stream.skipWhitespace2() || stream.eos()) { this.lastAttributeName = ''; // remember that we have seen a whitespace return { type: '' }; } else { if (this.lastAttributeName === '') { var name = this.nextAttributeName(stream); if (name.length > 0) { this.lastAttributeName = name; this.kind = States.AttributeName; return { type: htmlTokenTypes.ATTRIB_NAME }; } } if (stream.advanceIfString2('/>')) { this.kind = States.Content; return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true }; } if (stream.advanceIfCharCode2('>'.charCodeAt(0))) { if (tagsEmbeddingContent.indexOf(this.lastTagName) !== -1) { this.kind = States.WithinEmbeddedContent; return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true }; } else { this.kind = States.Content; return { type: htmlTokenTypes.DELIM_START, dontMergeWithPrev: true }; } } else { stream.next2(); return { type: '' }; } } case States.AttributeName: if (stream.skipWhitespace2() || stream.eos()){ return { type: '' }; } if (stream.advanceIfCharCode2('='.charCodeAt(0))) { this.kind = States.AttributeValue; return { type: htmlTokenTypes.DELIM_ASSIGN }; } else { this.kind = States.WithinTag; this.lastAttributeName = ''; return this.tokenize(stream); // no advance yet - jump to WithinTag } case States.AttributeValue: if (stream.eos()) { return { type: '' }; } if(stream.skipWhitespace2()) { if (this.attributeValueQuote === '"' || this.attributeValueQuote === '\'') { // We are inside the quotes of an attribute value return { type: htmlTokenTypes.ATTRIB_VALUE }; } return { type: '' }; } // We are in a attribute value if (this.attributeValueQuote === '"' || this.attributeValueQuote === '\'') { if (this.attributeValueLength === 1 && ('script' === this.lastTagName || 'style' === this.lastTagName) && 'type' === this.lastAttributeName) { let attributeValue = stream.advanceUntilString(this.attributeValueQuote, true); if (attributeValue.length > 0) { this.embeddedContentType = this.unquote(attributeValue); this.kind = States.WithinTag; this.attributeValueLength = 0; this.attributeValueQuote = ''; return { type: htmlTokenTypes.ATTRIB_VALUE }; } } else { if (stream.advanceIfCharCode2(this.attributeValueQuote.charCodeAt(0))) { this.kind = States.WithinTag; this.attributeValueLength = 0; this.attributeValueQuote = ''; this.lastAttributeName = null; } else { stream.next(); this.attributeValueLength++; } return { type: htmlTokenTypes.ATTRIB_VALUE }; } } else { let attributeValue = stream.advanceIfRegExp(/^[^\s"'`=<>]+/); if (attributeValue.length > 0) { this.kind = States.WithinTag; this.lastAttributeName = null; return { type: htmlTokenTypes.ATTRIB_VALUE }; } var ch = stream.peek(); if (ch === '\'' || ch === '"') { this.attributeValueQuote = ch; this.attributeValueLength = 1; stream.next2(); return { type: htmlTokenTypes.ATTRIB_VALUE }; } else { this.kind = States.WithinTag; this.lastAttributeName = null; return this.tokenize(stream); // no advance yet - jump to WithinTag } } } stream.next2(); this.kind = States.Content; return { type: '' }; } private unquote(value:string):string { var start = 0; var end = value.length; if ('"' === value[0]) { start++; } if ('"' === value[end - 1]) { end--; } return value.substring(start, end); } } export class HTMLMode<W extends htmlWorker.HTMLWorker> extends CompatMode implements ITokenizationCustomization { public static LANG_CONFIG:LanguageConfiguration = { wordPattern: createWordRegExp('#-?%'), comments: { blockComment: ['<!--', '-->'] }, brackets: [ ['<!--', '-->'], ['<', '>'], ], __electricCharacterSupport: { embeddedElectricCharacters: ['*', '}', ']', ')'] }, autoClosingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: '\'', close: '\'' } ], surroundingPairs: [ { open: '"', close: '"' }, { open: '\'', close: '\'' } ], onEnterRules: [ { beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i, action: { indentAction: modes.IndentAction.IndentOutdent } }, { beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), action: { indentAction: modes.IndentAction.Indent } } ], }; public tokenizationSupport: modes.ITokenizationSupport; private modeService:IModeService; private _modeWorkerManager: ModeWorkerManager<W>; constructor( descriptor:modes.IModeDescriptor, @IInstantiationService instantiationService: IInstantiationService, @IModeService modeService: IModeService, @ICompatWorkerService compatWorkerService: ICompatWorkerService, @IWorkspaceContextService private workspaceContextService: IWorkspaceContextService, @IConfigurationService private configurationService: IConfigurationService ) { super(descriptor.id, compatWorkerService); this._modeWorkerManager = this._createModeWorkerManager(descriptor, instantiationService); this.modeService = modeService; this.tokenizationSupport = new TokenizationSupport(this, this, true); if (this.compatWorkerService && this.compatWorkerService.isInMainThread) { let updateConfiguration = () => { let opts = configurationService.getConfiguration<IHTMLConfiguration>('html'); this._configureWorker(opts); }; configurationService.onDidUpdateConfiguration((e) => updateConfiguration()); updateConfiguration(); } this._registerSupports(); } protected _registerSupports(): void { if (this.getId() !== 'html') { throw new Error('This method must be overwritten!'); } modes.SuggestRegistry.register(this.getId(), { triggerCharacters: ['.', ':', '<', '"', '=', '/'], provideCompletionItems: (model, position, token): Thenable<modes.ISuggestResult> => { return wireCancellationToken(token, this._provideCompletionItems(model.uri, position)); } }, true); modes.DocumentHighlightProviderRegistry.register(this.getId(), { provideDocumentHighlights: (model, position, token): Thenable<modes.DocumentHighlight[]> => { return wireCancellationToken(token, this._provideDocumentHighlights(model.uri, position)); } }, true); modes.DocumentRangeFormattingEditProviderRegistry.register(this.getId(), { provideDocumentRangeFormattingEdits: (model, range, options, token): Thenable<editorCommon.ISingleEditOperation[]> => { return wireCancellationToken(token, this._provideDocumentRangeFormattingEdits(model.uri, range, options)); } }, true); modes.LinkProviderRegistry.register(this.getId(), { provideLinks: (model, token): Thenable<modes.ILink[]> => { return wireCancellationToken(token, this.provideLinks(model.uri)); } }, true); LanguageConfigurationRegistry.register(this.getId(), HTMLMode.LANG_CONFIG); } protected _createModeWorkerManager(descriptor:modes.IModeDescriptor, instantiationService: IInstantiationService): ModeWorkerManager<W> { return new ModeWorkerManager<W>(descriptor, 'vs/languages/html/common/htmlWorker', 'HTMLWorker', null, instantiationService); } private _worker<T>(runner:(worker:W)=>winjs.TPromise<T>): winjs.TPromise<T> { return this._modeWorkerManager.worker(runner); } // TokenizationSupport public getInitialState():modes.IState { return new State(this, States.Content, '', '', '', '', 0); } public enterNestedMode(state:modes.IState):boolean { return state instanceof State && (<State>state).kind === States.WithinEmbeddedContent; } public getNestedMode(state:modes.IState): IEnteringNestedModeData { var result:modes.IMode = null; var htmlState:State = <State>state; var missingModePromise: winjs.Promise = null; if (htmlState.embeddedContentType !== null) { if (this.modeService.isRegisteredMode(htmlState.embeddedContentType)) { result = this.modeService.getMode(htmlState.embeddedContentType); if (!result) { missingModePromise = this.modeService.getOrCreateMode(htmlState.embeddedContentType); } } } else { var mimeType:string = null; if ('script' === htmlState.lastTagName) { mimeType = 'text/javascript'; } else if ('style' === htmlState.lastTagName) { mimeType = 'text/css'; } else { mimeType = 'text/plain'; } result = this.modeService.getMode(mimeType); } if (result === null) { result = this.modeService.getMode('text/plain'); } return { mode: result, missingModePromise: missingModePromise }; } public getLeavingNestedModeData(line:string, state:modes.IState):ILeavingNestedModeData { var tagName = (<State>state).lastTagName; var regexp = new RegExp('<\\/' + tagName + '\\s*>', 'i'); var match:any = regexp.exec(line); if (match !== null) { return { nestedModeBuffer: line.substring(0, match.index), bufferAfterNestedMode: line.substring(match.index), stateAfterNestedMode: new State(this, States.Content, '', '', '', '', 0) }; } return null; } static $_configureWorker = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._configureWorker); private _configureWorker(options:any): winjs.TPromise<void> { return this._worker((w) => w._doConfigure(options)); } protected provideLinks(resource:URI):winjs.TPromise<modes.ILink[]> { let workspace = this.workspaceContextService.getWorkspace(); let workspaceResource = workspace ? workspace.resource : null; return this._provideLinks(resource, workspaceResource); } static $_provideLinks = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideLinks); private _provideLinks(resource:URI, workspaceResource:URI):winjs.TPromise<modes.ILink[]> { return this._worker((w) => w.provideLinks(resource, workspaceResource)); } static $_provideDocumentRangeFormattingEdits = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideDocumentRangeFormattingEdits); private _provideDocumentRangeFormattingEdits(resource:URI, range:editorCommon.IRange, options:modes.FormattingOptions):winjs.TPromise<editorCommon.ISingleEditOperation[]> { return this._worker((w) => w.provideDocumentRangeFormattingEdits(resource, range, options)); } static $_provideDocumentHighlights = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideDocumentHighlights); protected _provideDocumentHighlights(resource:URI, position:editorCommon.IPosition, strict:boolean = false): winjs.TPromise<modes.DocumentHighlight[]> { return this._worker((w) => w.provideDocumentHighlights(resource, position, strict)); } static $_provideCompletionItems = CompatWorkerAttr(HTMLMode, HTMLMode.prototype._provideCompletionItems); protected _provideCompletionItems(resource:URI, position:editorCommon.IPosition):winjs.TPromise<modes.ISuggestResult> { return this._worker((w) => w.provideCompletionItems(resource, position)); } }
the_stack
import * as child_process from "child_process"; import * as fs from "fs-extra"; import { BookMetadata, projectAon, Language } from ".."; /** Tool to download book data from the Project Aon SVN */ export class BookData { /** * URL base directory for extra contents for this application. */ private static readonly EXTRA_TONI_CONTENTS_URL = "https://projectaon.org/staff/toni/extraContent-DONOTREMOVE"; /** URL for the PAON trunk (current version) */ private static readonly SVN_TRUNK_URL = "https://www.projectaon.org/data/trunk"; /** * The target directory root */ public static readonly TARGET_ROOT = "www/data/projectAon"; // BookData.LANGUAGES = ['en','es']; /** The book number 1-based index */ private bookNumber: number; /** Metadata about the book */ private bookMetadata: BookMetadata; /** The english book code */ private enCode: string; /** The spanish book code */ private esCode: string; /** Array with illustrations authors directories names */ private illAuthors: string[]; /** * Constructor * @param bookNumber The book number (1-based index) */ constructor(bookNumber: number) { this.bookNumber = bookNumber; this.bookMetadata = projectAon.supportedBooks[ bookNumber - 1 ]; this.enCode = this.bookMetadata.code_en; this.esCode = this.bookMetadata.code_es; this.illAuthors = this.bookMetadata.illustrators; } /** * Returns the SVN root for this book. * See projectAon.ts for an explanation */ private getSvnRoot(): string { if ( this.bookMetadata.revision === 0 ) { return "https://www.projectaon.org/data/tags/20151013"; } else { return "https://www.projectaon.org/data/trunk"; } } /** * Get the book code for a given language */ private getBookCode(language: Language): string { return language === Language.ENGLISH ? this.enCode : this.esCode; } /** * Get the local relative path for the book data */ private getBookDir(): string { return BookData.TARGET_ROOT + "/" + this.bookNumber; } /** * Get the the book XML file book name * @param language The language code (en/es) * @returns The book XML file name */ private getBookXmlName(language: Language) { return this.getBookCode( language ) + ".xml"; } /** * Get the SVN source path for the book XML, as it is configured on projectAon.ts * @param language The language code (en/es) * @param root Optional. The SVN root to use. If null, the current published version will be used * @returns The currently used book XML URL at the PAON web site */ private getXmlSvnSourcePath(language: Language, root: string = null): string { if ( !root ) { root = this.getSvnRoot(); } return root + "/" + language + "/xml/" + this.getBookXmlName( language ); } /** * Download the book XML for a given language * @param language The language code (en/es) */ private downloadXml(language: Language) { // Download the book XML const sourcePath = this.getXmlSvnSourcePath(language); const targetPath = this.getBookDir() + "/" + this.getBookXmlName( language ); const svnParams = [ "export" , sourcePath , targetPath ]; this.runSvnCommand( svnParams ); // Check if there are book patches // Patches are at [ROOT]/src/patches/projectAonPatches/, and they are downloaded by BookData.prototype.downloadPatches const patchFileName = this.getBookCode( language ) + "-" + this.bookMetadata.revision + ".diff"; const patchPath = "src/patches/projectAonPatches/" + patchFileName; if ( fs.existsSync( patchPath ) ) { console.log( "Applying patch " + patchFileName + " to " + targetPath ); // patch [options] [originalfile [patchfile]] child_process.execFileSync( "patch" , [ targetPath , patchPath ] , {stdio: [ 0, 1, 2 ]} ); } } /** * Download an author biography file */ private downloadAuthorBio(language: Language, bioFileName: string) { const sourcePath = this.getSvnRoot() + "/" + language + "/xml/" + bioFileName + ".inc"; const targetPath = this.getBookDir() + "/" + bioFileName + "-" + language + ".inc"; const svnParams = [ "export" , sourcePath , targetPath ]; this.runSvnCommand( svnParams ); } /** * Get the svn absolute URL for illustrations directory of a given author / language */ private getSvnIllustrationsDir( language: Language, author: string): string { const booksSet = language === Language.ENGLISH ? "lw" : "ls"; return this.getSvnRoot() + "/" + language + "/png/" + booksSet + "/" + this.getBookCode(language) + "/ill/" + author; } /** * Download illustrations */ private downloadIllustrations(language: Language, author: string) { const sourceSvnDir = this.getSvnIllustrationsDir(language, author); const targetDir = this.getBookDir() + "/ill_" + language; fs.mkdirSync( targetDir ); const svnParams = [ "--force", "export" , sourceSvnDir , targetDir ]; this.runSvnCommand( svnParams ); if ( this.bookNumber === 9 && language === Language.ENGLISH ) { this.book9ObjectIllustrations(); } } /** * Download extra book 9 object illustrations. * On book 9, there is a illustrator change (Brian Williams). He did illustrations for objects that * exists on previous books. So, include on this book all existing objects illustrations */ private book9ObjectIllustrations() { // Already included on book 9: dagger.png, sword.png, mace.png, bow.png, food.png, potion.png, quiver.png, rope.png const targetDir = this.getBookDir() + "/ill_en"; // Not included on book 9, but in later books: const williamsIllustrations = { "axe.png" : "12tmod/ill/williams/axe.png", "spear.png" : "13tplor/ill/williams/spear.png", "bsword.png" : "17tdoi/ill/williams/bsword.png", "qstaff.png" : "12tmod/ill/williams/qurtstff.png" // NAME CHANGED!!! }; for (const illName of Object.keys(williamsIllustrations) ) { const svnSourcePath = this.getSvnRoot() + "/en/png/lw/" + williamsIllustrations[illName]; const targetPath = targetDir + "/" + illName; this.runSvnCommand( [ "export" , svnSourcePath , targetPath ] ); } // NOT included at any book: ssword.png, warhammr.png. Added to https://projectaon.org/staff/toni/extraContent-DONOTREMOVE const williamsIllustrationsExtra = [ BookData.EXTRA_TONI_CONTENTS_URL + "/ssword.png", BookData.EXTRA_TONI_CONTENTS_URL + "/warhammr.png" ]; for (const ill of williamsIllustrationsExtra) { BookData.downloadWithWGet( ill , targetDir ); } } /** * Download a file with wget * @param {string} url File URL to download * @param {string} targetDirectory Destination directory */ private static downloadWithWGet( url: string , targetDirectory: string ) { // wget https://projectaon.org/staff/toni/extraContent-DONOTREMOVE/ssword.png -P targetDirectory/ const params = [ url , "-P" , targetDirectory ]; console.log( "wget " + params.join( " " ) ); child_process.execFileSync( "wget" , params , {stdio: [0, 1, 2]} ); } /** * Download the book cover */ private downloadCover() { const coverPath = this.getSvnRoot() + "/en/jpeg/lw/" + this.getBookCode(Language.ENGLISH) + "/skins/ebook/cover.jpg"; const targetPath = this.getBookDir() + "/cover.jpg"; this.runSvnCommand( [ "export" , coverPath , targetPath ] ); } private zipBook() { // Zip the book // Go to books dir const curDir = process.cwd(); process.chdir(BookData.TARGET_ROOT); const txtBookNumber = this.bookNumber.toString(); child_process.execFileSync( "zip" , ["-r" , txtBookNumber + ".zip" , txtBookNumber] , {stdio: [0, 1, 2]} ); // Go back process.chdir(curDir); } public downloadBookData() { const bookDir = BookData.TARGET_ROOT + "/" + this.bookNumber; console.log("Re-creating directory " + bookDir); fs.removeSync( bookDir ); fs.mkdirSync( bookDir ); this.downloadCover(); for (const langKey of Object.keys(Language)) { const language = Language[langKey]; if (!this.getBookCode( language )) { // Skip books without given language continue; } // Download authors biographies this.bookMetadata.biographies.forEach( (authorBio) => { this.downloadAuthorBio(language, authorBio); }); this.downloadXml(language); this.illAuthors.forEach( (author) => { this.downloadIllustrations(language , author); }); this.downloadCombatTablesImages(language); } this.zipBook(); } private downloadCombatTablesImages(language: Language) { const sourceSvnDir = this.getSvnIllustrationsDir(language, "blake"); const targetDir = this.getBookDir() + "/ill_" + language; this.runSvnCommand( [ "export" , sourceSvnDir + "/crtneg.png" , targetDir + "/crtneg.png" ] ); this.runSvnCommand( [ "export" , sourceSvnDir + "/crtpos.png" , targetDir + "/crtpos.png" ] ); } private runSvnCommand( params: string[] ) { if ( this.bookMetadata.revision ) { // Add the revision number params = [ "-r" , this.bookMetadata.revision.toString() ].concat( params ); } console.log( "svn " + params.join( " " ) ); child_process.execFileSync( "svn" , params , {stdio: [0, 1, 2]} ); } /** * Download book XML patches from PAON web site */ private downloadBooksXmlPatches() { const patchesDirectory = "src/patches/projectAonPatches"; if ( !fs.existsSync( patchesDirectory ) ) { console.log( "Creating PAON book xml patches directory: " + patchesDirectory ); fs.mkdirSync( patchesDirectory ); } const patchFileNames = [ "09ecdm-2655.diff" ]; for (const patchName of patchFileNames) { if ( !fs.existsSync( patchesDirectory + "/" + patchName ) ) { BookData.downloadWithWGet( BookData.EXTRA_TONI_CONTENTS_URL + "/" + patchName , patchesDirectory ); } } } /** * Check changes from the published app version with the trunk current version * @param {String} language Language to compare */ public reviewChangesCurrentVersion(language: Language) { // svn diff -x --ignore-all-space https://www.projectaon.org/data/tags/20151013/es/xml/01hdlo.xml https://www.projectaon.org/data/trunk/es/xml/01hdlo.xml | iconv -f ISO-8859-1 | dwdiff --diff-input -c | less -R // The currently publised version with the app let publishedWithAppSvnPath = this.getXmlSvnSourcePath(language); if ( this.bookMetadata.revision ) { publishedWithAppSvnPath += "@" + this.bookMetadata.revision; } // The latest version on the PAON site const currentVersionPath = this.getXmlSvnSourcePath(language, BookData.SVN_TRUNK_URL); const shellCommand = "svn diff -x --ignore-all-space " + publishedWithAppSvnPath + " " + currentVersionPath + " | iconv -f ISO-8859-1 | dwdiff --diff-input -c | less -R"; console.log( shellCommand ); child_process.spawn( "sh", ["-c", shellCommand], { stdio: "inherit" }); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { SharedPrivateLinkResources } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { SearchManagementClient } from "../searchManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { SharedPrivateLinkResource, SharedPrivateLinkResourcesListByServiceNextOptionalParams, SharedPrivateLinkResourcesListByServiceOptionalParams, SharedPrivateLinkResourcesCreateOrUpdateOptionalParams, SharedPrivateLinkResourcesCreateOrUpdateResponse, SharedPrivateLinkResourcesGetOptionalParams, SharedPrivateLinkResourcesGetResponse, SharedPrivateLinkResourcesDeleteOptionalParams, SharedPrivateLinkResourcesListByServiceResponse, SharedPrivateLinkResourcesListByServiceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing SharedPrivateLinkResources operations. */ export class SharedPrivateLinkResourcesImpl implements SharedPrivateLinkResources { private readonly client: SearchManagementClient; /** * Initialize a new instance of the class SharedPrivateLinkResources class. * @param client Reference to the service client */ constructor(client: SearchManagementClient) { this.client = client; } /** * Gets a list of all shared private link resources managed by the given service. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param options The options parameters. */ public listByService( resourceGroupName: string, searchServiceName: string, options?: SharedPrivateLinkResourcesListByServiceOptionalParams ): PagedAsyncIterableIterator<SharedPrivateLinkResource> { const iter = this.listByServicePagingAll( resourceGroupName, searchServiceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByServicePagingPage( resourceGroupName, searchServiceName, options ); } }; } private async *listByServicePagingPage( resourceGroupName: string, searchServiceName: string, options?: SharedPrivateLinkResourcesListByServiceOptionalParams ): AsyncIterableIterator<SharedPrivateLinkResource[]> { let result = await this._listByService( resourceGroupName, searchServiceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByServiceNext( resourceGroupName, searchServiceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByServicePagingAll( resourceGroupName: string, searchServiceName: string, options?: SharedPrivateLinkResourcesListByServiceOptionalParams ): AsyncIterableIterator<SharedPrivateLinkResource> { for await (const page of this.listByServicePagingPage( resourceGroupName, searchServiceName, options )) { yield* page; } } /** * Initiates the creation or update of a shared private link resource managed by the search service in * the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param sharedPrivateLinkResourceName The name of the shared private link resource managed by the * Azure Cognitive Search service within the specified resource group. * @param sharedPrivateLinkResource The definition of the shared private link resource to create or * update. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, searchServiceName: string, sharedPrivateLinkResourceName: string, sharedPrivateLinkResource: SharedPrivateLinkResource, options?: SharedPrivateLinkResourcesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<SharedPrivateLinkResourcesCreateOrUpdateResponse>, SharedPrivateLinkResourcesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<SharedPrivateLinkResourcesCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, sharedPrivateLinkResource, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "azure-async-operation" }); } /** * Initiates the creation or update of a shared private link resource managed by the search service in * the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param sharedPrivateLinkResourceName The name of the shared private link resource managed by the * Azure Cognitive Search service within the specified resource group. * @param sharedPrivateLinkResource The definition of the shared private link resource to create or * update. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, searchServiceName: string, sharedPrivateLinkResourceName: string, sharedPrivateLinkResource: SharedPrivateLinkResource, options?: SharedPrivateLinkResourcesCreateOrUpdateOptionalParams ): Promise<SharedPrivateLinkResourcesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, sharedPrivateLinkResource, options ); return poller.pollUntilDone(); } /** * Gets the details of the shared private link resource managed by the search service in the given * resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param sharedPrivateLinkResourceName The name of the shared private link resource managed by the * Azure Cognitive Search service within the specified resource group. * @param options The options parameters. */ get( resourceGroupName: string, searchServiceName: string, sharedPrivateLinkResourceName: string, options?: SharedPrivateLinkResourcesGetOptionalParams ): Promise<SharedPrivateLinkResourcesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options }, getOperationSpec ); } /** * Initiates the deletion of the shared private link resource from the search service. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param sharedPrivateLinkResourceName The name of the shared private link resource managed by the * Azure Cognitive Search service within the specified resource group. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, searchServiceName: string, sharedPrivateLinkResourceName: string, options?: SharedPrivateLinkResourcesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "azure-async-operation" }); } /** * Initiates the deletion of the shared private link resource from the search service. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param sharedPrivateLinkResourceName The name of the shared private link resource managed by the * Azure Cognitive Search service within the specified resource group. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, searchServiceName: string, sharedPrivateLinkResourceName: string, options?: SharedPrivateLinkResourcesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options ); return poller.pollUntilDone(); } /** * Gets a list of all shared private link resources managed by the given service. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param options The options parameters. */ private _listByService( resourceGroupName: string, searchServiceName: string, options?: SharedPrivateLinkResourcesListByServiceOptionalParams ): Promise<SharedPrivateLinkResourcesListByServiceResponse> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, options }, listByServiceOperationSpec ); } /** * ListByServiceNext * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param nextLink The nextLink from the previous successful call to the ListByService method. * @param options The options parameters. */ private _listByServiceNext( resourceGroupName: string, searchServiceName: string, nextLink: string, options?: SharedPrivateLinkResourcesListByServiceNextOptionalParams ): Promise<SharedPrivateLinkResourcesListByServiceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, nextLink, options }, listByServiceNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResource }, 201: { bodyMapper: Mappers.SharedPrivateLinkResource }, 202: { bodyMapper: Mappers.SharedPrivateLinkResource }, 204: { bodyMapper: Mappers.SharedPrivateLinkResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.sharedPrivateLinkResource, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId, Parameters.sharedPrivateLinkResourceName ], headerParameters: [ Parameters.accept, Parameters.clientRequestId, Parameters.contentType ], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResource }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId, Parameters.sharedPrivateLinkResourceName ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId, Parameters.sharedPrivateLinkResourceName ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const listByServiceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const listByServiceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer };
the_stack
import {fetchRunsSucceeded} from '../../runs/actions'; import {buildHparamsAndMetadata} from '../../runs/data_source/testing'; import {buildRun} from '../../runs/store/testing'; import {DiscreteFilter, DomainType, IntervalFilter} from '../types'; import * as actions from './hparams_actions'; import {reducers} from './hparams_reducers'; import { buildDiscreteFilter, buildHparamSpec, buildHparamsState, buildIntervalFilter, buildMetricSpec, buildSpecs, buildFilterState, } from './testing'; describe('hparams/_redux/hparams_reducers_test', () => { describe('fetchRunsSucceeded', () => { it('sets hparams and metrics specs', () => { const state = buildHparamsState({ ...buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'h1'})], defaultFilters: new Map([ [ 'h1', buildIntervalFilter({ filterLowerValue: 0.5, filterUpperValue: 0.7, }), ], ]), }, metric: { specs: [buildMetricSpec({tag: 'm1'})], defaultFilters: new Map([ [ 'm1', buildIntervalFilter({ filterLowerValue: 0.5, filterUpperValue: 0.5, }), ], ]), }, }), }); const action = fetchRunsSucceeded({ experimentIds: [], runsForAllExperiments: [], newRunsAndMetadata: { foo: { runs: [ buildRun({id: 'r1'}), buildRun({id: 'r2'}), buildRun({id: 'r3'}), ], metadata: buildHparamsAndMetadata({ runToHparamsAndMetrics: { r1: { hparams: [], metrics: [{tag: 'm1', trainingStep: 1, value: 1}], }, r2: { hparams: [], metrics: [{tag: 'm1', trainingStep: 1, value: 0.1}], }, r3: { hparams: [], metrics: [{tag: 'm2', trainingStep: 1, value: 100}], }, }, hparamSpecs: [ buildHparamSpec({ name: 'h1', domain: {type: DomainType.INTERVAL, minValue: 0, maxValue: 1}, }), buildHparamSpec({ name: 'h2', domain: { type: DomainType.DISCRETE, values: ['a', 'b', 'c'], }, }), ], metricSpecs: [ buildMetricSpec({tag: 'm1'}), buildMetricSpec({tag: 'm2'}), buildMetricSpec({tag: 'm3'}), ], }), }, }, }); const nextState = reducers(state, action); expect(nextState.specs['foo'].hparam.specs).toEqual([ buildHparamSpec({ name: 'h1', domain: {type: DomainType.INTERVAL, minValue: 0, maxValue: 1}, }), buildHparamSpec({ name: 'h2', domain: { type: DomainType.DISCRETE, values: ['a', 'b', 'c'], }, }), ]); expect(nextState.specs['foo'].hparam.defaultFilters).toEqual( new Map<string, DiscreteFilter | IntervalFilter>([ [ 'h1', buildIntervalFilter({ minValue: 0, maxValue: 1, filterLowerValue: 0, filterUpperValue: 1, }), ], [ 'h2', buildDiscreteFilter({ possibleValues: ['a', 'b', 'c'], filterValues: ['a', 'b', 'c'], }), ], ]) ); expect(nextState.specs['foo'].metric.specs).toEqual([ buildMetricSpec({tag: 'm1'}), buildMetricSpec({tag: 'm2'}), buildMetricSpec({tag: 'm3'}), ]); expect(nextState.specs['foo'].metric.defaultFilters).toEqual( new Map([ [ 'm1', buildIntervalFilter({ minValue: 0.1, maxValue: 1, filterLowerValue: 0.1, filterUpperValue: 1, }), ], [ 'm2', buildIntervalFilter({ minValue: 100, maxValue: 100, filterLowerValue: 100, filterUpperValue: 100, }), ], [ 'm3', buildIntervalFilter({ minValue: 0, maxValue: 0, filterLowerValue: 0, filterUpperValue: 0, }), ], ]) ); }); }); describe('hparamsIntervalHparamFilterChanged', () => { it('sets initial interval hparam filter', () => { const state = buildHparamsState({ ...buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([['dropout', buildIntervalFilter()]]), }, }), }); const nextState = reducers( state, actions.hparamsIntervalHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }) ); expect(nextState.filters['["foo"]'].hparams).toEqual( new Map([ [ 'dropout', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }), ], ]) ); }); it('updates existing interval hparam filter', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([['dropout', buildIntervalFilter()]]), }, }), buildFilterState(['foo'], { hparams: new Map([ [ 'dropout', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.003, filterUpperValue: 0.5, }), ], ]), }) ); const nextState = reducers( state, actions.hparamsIntervalHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }) ); expect(nextState.filters['["foo"]'].hparams).toEqual( new Map([ [ 'dropout', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }), ], ]) ); }); it('throws error when setting interval hparam that did not exist', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([['dropout', buildIntervalFilter()]]), }, }) ); const action = actions.hparamsIntervalHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'random_seed', includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }); expect(() => reducers(state, action)).toThrow(); }); it('throws when setting interval on discrete hparam', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([['dropout', buildDiscreteFilter()]]), }, }) ); const action = actions.hparamsIntervalHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterLowerValue: 0.5, filterUpperValue: 0.5, }); expect(() => reducers(state, action)).toThrow(); }); }); describe('hparamsDiscreteHparamFilterChanged', () => { it('sets initial discrete hparam filter', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([ [ 'dropout', buildDiscreteFilter({ includeUndefined: true, filterValues: [1, 10, 100], }), ], ]), }, }), buildFilterState(['foo'], {hparams: new Map()}) ); const nextState = reducers( state, actions.hparamsDiscreteHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterValues: [10, 100], }) ); expect(nextState.filters['["foo"]'].hparams).toEqual( new Map([ [ 'dropout', buildDiscreteFilter({ includeUndefined: true, filterValues: [10, 100], }), ], ]) ); }); it('updates existing discrete hparam filter', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([ [ 'dropout', buildDiscreteFilter({ includeUndefined: true, filterValues: [1, 10, 100], }), ], ]), }, }), buildFilterState(['foo'], { hparams: new Map([ [ 'dropout', buildDiscreteFilter({ includeUndefined: true, filterValues: [2, 200], }), ], ]), }) ); const nextState = reducers( state, actions.hparamsDiscreteHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterValues: [10, 100], }) ); expect(nextState.filters['["foo"]'].hparams).toEqual( new Map([ [ 'dropout', buildDiscreteFilter({ includeUndefined: true, filterValues: [10, 100], }), ], ]) ); }); it('throws error when setting discrete hparam that did not exist', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([]), }, }), buildFilterState(['foo'], {hparams: new Map()}) ); const action = actions.hparamsDiscreteHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'optimizer', includeUndefined: true, filterValues: ['adam', 'adagrad'], }); expect(() => reducers(state, action)).toThrow(); }); it('throws when setting discrete change on interval hparam', () => { const state = buildHparamsState( buildSpecs('foo', { hparam: { specs: [buildHparamSpec({name: 'dropout'})], defaultFilters: new Map([['dropout', buildIntervalFilter()]]), }, }), buildFilterState(['foo'], { hparams: new Map([['dropout', buildIntervalFilter()]]), }) ); const action = actions.hparamsDiscreteHparamFilterChanged({ experimentIds: ['foo'], hparamName: 'dropout', includeUndefined: true, filterValues: ['adam', 'adagrad'], }); expect(() => reducers(state, action)).toThrow(); }); }); describe('hparamsMetricFilterChanged', () => { it('sets initial metric filters', () => { const state = buildHparamsState( buildSpecs('foo', { metric: { specs: [buildMetricSpec({tag: 'loss'})], defaultFilters: new Map([ [ 'loss', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.2, filterUpperValue: 0.5, }), ], ]), }, }) ); const nextState = reducers( state, actions.hparamsMetricFilterChanged({ experimentIds: ['foo'], metricTag: 'loss', includeUndefined: false, filterLowerValue: 0.1, filterUpperValue: 0.5, }) ); expect(nextState.filters['["foo"]'].metrics).toEqual( new Map([ [ 'loss', buildIntervalFilter({ includeUndefined: false, filterLowerValue: 0.1, filterUpperValue: 0.5, }), ], ]) ); }); it('updates existing metric filters', () => { const state = buildHparamsState( buildSpecs('foo', { metric: { specs: [buildMetricSpec({tag: 'loss'})], defaultFilters: new Map([ [ 'loss', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.2, filterUpperValue: 0.5, }), ], ]), }, }), buildFilterState(['foo'], { metrics: new Map([ [ 'loss', buildIntervalFilter({ includeUndefined: true, filterLowerValue: 0.2, filterUpperValue: 0.5, }), ], ]), }) ); const nextState = reducers( state, actions.hparamsMetricFilterChanged({ experimentIds: ['foo'], metricTag: 'loss', includeUndefined: false, filterLowerValue: 0.1, filterUpperValue: 0.5, }) ); expect(nextState.filters['["foo"]'].metrics).toEqual( new Map([ [ 'loss', buildIntervalFilter({ includeUndefined: false, filterLowerValue: 0.1, filterUpperValue: 0.5, }), ], ]) ); }); it('throws error if it sets filter that does not exist', () => { const state = buildHparamsState( buildSpecs('foo', { metric: { specs: [buildMetricSpec({tag: 'loss'})], defaultFilters: new Map(), }, }) ); const action = actions.hparamsMetricFilterChanged({ experimentIds: ['foo'], metricTag: 'accuracy', includeUndefined: true, filterLowerValue: 0, filterUpperValue: 1, }); expect(() => reducers(state, action)).toThrow(); }); }); });
the_stack
export interface paths { "/2/users": { /** This endpoint returns information about users. Specify users by their ID. */ get: operations["findUsersById"]; }; "/2/users/{id}": { /** This endpoint returns information about a user. Specify user by ID. */ get: operations["findUserById"]; }; "/2/users/by": { /** This endpoint returns information about users. Specify users by their username. */ get: operations["findUsersByUsername"]; }; "/2/users/me": { /** This endpoint returns information about the requesting user. */ get: operations["findMyUser"]; }; "/2/users/by/username/{username}": { /** This endpoint returns information about a user. Specify user by username. */ get: operations["findUserByUsername"]; }; "/2/users/{id}/blocking": { /** Returns a list of users that are blocked by the provided user ID */ get: operations["usersIdBlocking"]; /** Causes the user (in the path) to block the target user. The user (in the path) must match the user context authorizing the request */ post: operations["usersIdBlock"]; }; "/2/users/{source_user_id}/blocking/{target_user_id}": { /** Causes the source user to unblock the target user. The source user must match the user context authorizing the request */ delete: operations["usersIdUnblock"]; }; "/2/users/{id}/bookmarks": { /** Returns Tweet objects that have been bookmarked by the requesting user */ get: operations["getUsersIdBookmarks"]; /** Adds a Tweet (ID in the body) to the requesting user's (in the path) bookmarks */ post: operations["postUsersIdBookmarks"]; }; "/2/users/{id}/bookmarks/{tweet_id}": { /** Removes a Tweet from the requesting user's bookmarked Tweets. */ delete: operations["usersIdBookmarksDelete"]; }; "/2/users/{source_user_id}/muting/{target_user_id}": { /** Causes the source user to unmute the target user. The source user must match the user context authorizing the request */ delete: operations["usersIdUnmute"]; }; "/2/users/{id}/muting": { /** Returns a list of users that are muted by the provided user ID */ get: operations["usersIdMuting"]; /** Causes the user (in the path) to mute the target user. The user (in the path) must match the user context authorizing the request */ post: operations["usersIdMute"]; }; "/2/users/{id}/followers": { /** Returns a list of users that follow the provided user ID */ get: operations["usersIdFollowers"]; }; "/2/users/{id}/following": { /** Returns a list of users that are being followed by the provided user ID */ get: operations["usersIdFollowing"]; /** Causes the user(in the path) to follow, or “request to follow” for protected users, the target user. The user(in the path) must match the user context authorizing the request */ post: operations["usersIdFollow"]; }; "/2/users/{source_user_id}/following/{target_user_id}": { /** Causes the source user to unfollow the target user. The source user must match the user context authorizing the request */ delete: operations["usersIdUnfollow"]; }; "/2/users/{id}/followed_lists": { /** Returns a user's followed Lists. */ get: operations["userFollowedLists"]; /** Causes a user to follow a List. */ post: operations["listUserFollow"]; }; "/2/users/{id}/followed_lists/{list_id}": { /** Causes a user to unfollow a List. */ delete: operations["listUserUnfollow"]; }; "/2/users/{id}/list_memberships": { /** Get a User's List Memberships. */ get: operations["getUserListMemberships"]; }; "/2/users/{id}/owned_lists": { /** Get a User's Owned Lists. */ get: operations["listUserOwnedLists"]; }; "/2/users/{id}/pinned_lists": { /** Get a User's Pinned Lists. */ get: operations["listUserPinnedLists"]; /** Causes a user to pin a List. */ post: operations["listUserPin"]; }; "/2/users/{id}/pinned_lists/{list_id}": { /** Causes a user to remove a pinned List. */ delete: operations["listUserUnpin"]; }; "/2/tweets": { /** Returns a variety of information about the Tweet specified by the requested ID. */ get: operations["findTweetsById"]; /** Causes the user to create a tweet under the authorized account. */ post: operations["createTweet"]; }; "/2/tweets/{id}": { /** Returns a variety of information about the Tweet specified by the requested ID. */ get: operations["findTweetById"]; /** Delete specified Tweet (in the path) by ID. */ delete: operations["deleteTweetById"]; }; "/2/tweets/{id}/quote_tweets": { /** Returns a variety of information about each tweet that quotes the Tweet specified by the requested ID. */ get: operations["findTweetsThatQuoteATweet"]; }; "/2/tweets/{id}/hidden": { /** Hides or unhides a reply to an owned conversation. */ put: operations["hideReplyById"]; }; "/2/tweets/search/recent": { /** Returns Tweets from the last 7 days that match a search query. */ get: operations["tweetsRecentSearch"]; }; "/2/tweets/search/all": { /** Returns Tweets that match a search query. */ get: operations["tweetsFullarchiveSearch"]; }; "/2/tweets/search/stream": { /** Streams Tweets matching the stream's active rule set. */ get: operations["searchStream"]; }; "/2/tweets/search/stream/rules": { /** Returns rules from a user's active rule set. Users can fetch all of their rules or a subset, specified by the provided rule ids. */ get: operations["getRules"]; /** Add or delete rules from a user's active rule set. Users can provide unique, optionally tagged rules to add. Users can delete their entire rule set or a subset specified by rule ids or values. */ post: operations["addOrDeleteRules"]; }; "/2/tweets/sample/stream": { /** Streams a deterministic 1% of public Tweets. */ get: operations["sampleStream"]; }; "/2/openapi.json": { /** Full open api spec in JSON format. (See https://github.com/OAI/OpenAPI-Specification/blob/master/README.md) */ get: operations["getOpenApiSpec"]; }; "/2/users/{id}/timelines/reverse_chronological": { /** Returns Tweet objects that appears in the provided User ID's home timeline */ get: operations["usersIdTimeline"]; }; "/2/users/{id}/tweets": { /** Returns a list of Tweets authored by the provided User ID */ get: operations["usersIdTweets"]; }; "/2/users/{id}/mentions": { /** Returns Tweet objects that mention username associated to the provided User ID */ get: operations["usersIdMentions"]; }; "/2/users/{id}/likes": { /** Causes the user (in the path) to like the specified tweet. The user in the path must match the user context authorizing the request. */ post: operations["usersIdLike"]; }; "/2/users/{id}/likes/{tweet_id}": { /** Causes the user (in the path) to unlike the specified tweet. The user must match the user context authorizing the request */ delete: operations["usersIdUnlike"]; }; "/2/users/{id}/liked_tweets": { /** Returns a list of Tweets liked by the provided User ID */ get: operations["usersIdLikedTweets"]; }; "/2/tweets/{id}/liking_users": { /** Returns a list of users that have liked the provided Tweet ID */ get: operations["tweetsIdLikingUsers"]; }; "/2/tweets/{id}/retweeted_by": { /** Returns a list of users that have retweeted the provided Tweet ID */ get: operations["tweetsIdRetweetingUsers"]; }; "/2/users/{id}/retweets": { /** Causes the user (in the path) to retweet the specified tweet. The user in the path must match the user context authorizing the request. */ post: operations["usersIdRetweets"]; }; "/2/users/{id}/retweets/{source_tweet_id}": { /** Causes the user (in the path) to unretweet the specified tweet. The user must match the user context authorizing the request */ delete: operations["usersIdUnretweets"]; }; "/2/tweets/counts/recent": { /** Returns Tweet Counts from the last 7 days that match a search query. */ get: operations["tweetCountsRecentSearch"]; }; "/2/tweets/counts/all": { /** Returns Tweet Counts that match a search query. */ get: operations["tweetCountsFullArchiveSearch"]; }; "/2/compliance/jobs": { /** Returns recent compliance jobs for a given job type and optional job status */ get: operations["listBatchComplianceJobs"]; /** Creates a compliance for the given job type */ post: operations["createBatchComplianceJob"]; }; "/2/compliance/jobs/{id}": { /** Returns a single compliance job by ID */ get: operations["getBatchComplianceJob"]; }; "/2/lists": { /** Creates a new List. */ post: operations["listIdCreate"]; }; "/2/lists/{id}": { /** Returns a List */ get: operations["listIdGet"]; /** Update a List that you own. */ put: operations["listIdUpdate"]; /** Delete a List that you own. */ delete: operations["listIdDelete"]; }; "/2/lists/{id}/followers": { /** Returns a list of users that follow a List by the provided List ID */ get: operations["listGetFollowers"]; }; "/2/lists/{id}/members": { /** Returns a list of users that are members of a List by the provided List ID */ get: operations["listGetMembers"]; /** Causes a user to become a member of a List. */ post: operations["listAddMember"]; }; "/2/lists/{id}/members/{user_id}": { /** Causes a user to be removed from the members of a List. */ delete: operations["listRemoveMember"]; }; "/2/lists/{id}/tweets": { /** Returns a list of Tweets associated with the provided List ID */ get: operations["listsIdTweets"]; }; "/2/spaces/{id}": { /** Returns a variety of information about the Space specified by the requested ID */ get: operations["findSpaceById"]; }; "/2/spaces": { /** Returns a variety of information about the Spaces specified by the requested IDs */ get: operations["findSpacesByIds"]; }; "/2/spaces/by/creator_ids": { /** Returns a variety of information about the Spaces created by the provided User IDs */ get: operations["findSpacesByCreatorIds"]; }; "/2/spaces/search": { /** Returns Spaces that match the provided query. */ get: operations["searchSpaces"]; }; "/2/spaces/{id}/tweets": { /** Retrieves tweets shared in the specified space */ get: operations["spaceTweets"]; }; "/2/spaces/{id}/buyers": { /** Retrieves the list of users who purchased a ticket to the given space */ get: operations["spaceBuyers"]; }; } export interface components { schemas: { /** @description The height of the media in pixels */ MediaHeight: number; /** @description The width of the media in pixels */ MediaWidth: number; /** @description HTTP Status Code. */ HTTPStatusCode: number; /** @description Annotation inferred from the tweet text. */ ContextAnnotation: { domain: components["schemas"]["ContextAnnotationDomainFields"]; entity: components["schemas"]["ContextAnnotationEntityFields"]; }; /** @description Represents the data for the context annotation domain. */ ContextAnnotationDomainFields: { /** @description The unique id for a context annotation domain. */ id: string; /** @description Name of the context annotation domain. */ name?: string; /** @description Description of the context annotation domain. */ description?: string; }; /** @description Represents the data for the context annotation entity. */ ContextAnnotationEntityFields: { /** @description The unique id for a context annotation entity. */ id: string; /** @description Name of the context annotation entity. */ name?: string; /** @description Description of the context annotation entity. */ description?: string; }; /** * Format: uri * @description A validly formatted URL. * @example https://developer.twitter.com/en/docs/twitter-api */ URL: string; /** @description Represent a boundary range (start and end index) for a recognized entity (for example a hashtag or a mention). `start` must be smaller than `end`. The start index is inclusive, the end index is exclusive. */ EntityIndicesInclusiveExclusive: { /** * @description Index (zero-based) at which position this entity starts. The index is inclusive. * @example 50 */ start: number; /** * @description Index (zero-based) at which position this entity ends. The index is exclusive. * @example 61 */ end: number; }; /** @description Represent a boundary range (start and end index) for a recognized entity (for example a hashtag or a mention). `start` must be smaller than `end`. The start index is inclusive, the end index is inclusive. */ EntityIndicesInclusiveInclusive: { /** * @description Index (zero-based) at which position this entity starts. The index is inclusive. * @example 50 */ start: number; /** * @description Index (zero-based) at which position this entity ends. The index is inclusive. * @example 61 */ end: number; }; /** @description Represent the portion of text recognized as a URL. */ URLFields: { url: components["schemas"]["URL"]; expanded_url?: components["schemas"]["URL"]; /** * @description The URL as displayed in the Twitter client. * @example twittercommunity.com/t/introducing-… */ display_url?: string; /** * Format: uri * @description Fully resolved url * @example https://twittercommunity.com/t/introducing-the-v2-follow-lookup-endpoints/147118 */ unwound_url?: string; status?: components["schemas"]["HTTPStatusCode"]; /** * @description Title of the page the URL points to. * @example Introducing the v2 follow lookup endpoints */ title?: string; /** * @description Description of the URL landing page. * @example This is a description of the website. */ description?: string; images?: components["schemas"]["URLImage"][]; media_key?: components["schemas"]["MediaKey"]; }; /** @description Represent the portion of text recognized as a URL, and its start and end position within the text. */ UrlEntity: components["schemas"]["EntityIndicesInclusiveExclusive"] & components["schemas"]["URLFields"]; /** @description Represent the information for the URL image */ URLImage: { url?: components["schemas"]["URL"]; height?: components["schemas"]["MediaHeight"]; width?: components["schemas"]["MediaWidth"]; }; /** @description Represent the portion of text recognized as a Hashtag, and its start and end position within the text. */ HashtagFields: { /** * @description The text of the Hashtag * @example MondayMotivation */ tag: string; }; HashtagEntity: components["schemas"]["EntityIndicesInclusiveExclusive"] & components["schemas"]["HashtagFields"]; /** @description Represent the portion of text recognized as a Cashtag, and its start and end position within the text. */ CashtagFields: { /** @example TWTR */ tag: string; }; CashtagEntity: components["schemas"]["EntityIndicesInclusiveExclusive"] & components["schemas"]["CashtagFields"]; /** @description Represent the portion of text recognized as a User mention, and its start and end position within the text. */ MentionFields: { username: components["schemas"]["UserName"]; id: components["schemas"]["UserID"]; }; MentionEntity: components["schemas"]["EntityIndicesInclusiveExclusive"] & components["schemas"]["MentionFields"]; FullTextEntities: { urls?: components["schemas"]["UrlEntity"][]; hashtags?: components["schemas"]["HashtagEntity"][]; mentions?: components["schemas"]["MentionEntity"][]; cashtags?: components["schemas"]["CashtagEntity"][]; }; /** * @description Unique identifier of this Tweet. This is returned as a string in order to avoid complications with languages and tools that cannot handle large integers. * @example 1346889436626259968 */ TweetID: string; /** * @description The content of the Tweet. * @example Learn how to use the user Tweet timeline and user mention timeline endpoints in the Twitter API v2 to explore Tweet\u2026 https:\/\/t.co\/56a0vZUx7i */ TweetText: string; /** * @description Unique identifier of this User. This is returned as a string in order to avoid complications with languages and tools that cannot handle large integers. * @example 2244994945 */ UserID: string; /** * @description The unique identifier of this Space. * @example 1SLjjRYNejbKM */ SpaceID: string; /** * @description Shows who can reply a Tweet. Fields returned are everyone, mentioned_users, and following. * @enum {string} */ ReplySettings: "everyone" | "mentionedUsers" | "following" | "other"; Error: { /** Format: int32 */ code: number; message: string; }; Expansions: { users?: components["schemas"]["User"][]; tweets?: components["schemas"]["Tweet"][]; places?: components["schemas"]["Place"][]; media?: components["schemas"]["Media"][]; polls?: components["schemas"]["Poll"][]; }; /** @example [object Object] */ Tweet: { id: components["schemas"]["TweetID"]; /** * Format: date-time * @description Creation time of the Tweet. * @example 2021-01-06T18:40:40.000Z */ created_at?: string; text: components["schemas"]["TweetText"]; author_id?: components["schemas"]["UserID"]; in_reply_to_user_id?: components["schemas"]["UserID"]; conversation_id?: components["schemas"]["TweetID"]; reply_settings?: components["schemas"]["ReplySettings"]; /** @description A list of Tweets this Tweet refers to. For example, if the parent Tweet is a Retweet, a Quoted Tweet or a Reply, it will include the related Tweet referenced to by its parent. */ referenced_tweets?: { /** @enum {string} */ type: "retweeted" | "quoted" | "replied_to"; id: components["schemas"]["TweetID"]; }[]; /** @description Specifies the type of attachments (if any) present in this Tweet. */ attachments?: { /** @description A list of Media Keys for each one of the media attachments (if media are attached). */ media_keys?: components["schemas"]["MediaKey"][]; /** @description A list of poll IDs (if polls are attached). */ poll_ids?: components["schemas"]["PollId"][]; }; context_annotations?: components["schemas"]["ContextAnnotation"][]; withheld?: components["schemas"]["TweetWithheld"]; /** @description The location tagged on the Tweet, if the user provided one. */ geo?: { coordinates?: components["schemas"]["Point"]; place_id?: components["schemas"]["PlaceId"]; }; entities?: components["schemas"]["FullTextEntities"]; /** @description Engagement metrics for the Tweet at the time of the request. */ public_metrics?: { /** @description Number of times this Tweet has been Retweeted. */ retweet_count: number; /** @description Number of times this Tweet has been replied to. */ reply_count: number; /** @description Number of times this Tweet has been liked. */ like_count: number; /** @description Number of times this Tweet has been quoted. */ quote_count?: number; }; /** @description Indicates if this Tweet contains URLs marked as sensitive, for example content suitable for mature audiences. */ possibly_sensitive?: boolean; /** * @description Language of the Tweet, if detected by Twitter. Returned as a BCP47 language tag. * @example en */ lang?: string; /** @description The name of the app the user Tweeted from. */ source?: string; /** @description Nonpublic engagement metrics for the Tweet at the time of the request. */ non_public_metrics?: { /** * Format: int32 * @description Number of times this Tweet has been viewed. */ impression_count?: number; }; /** @description Promoted nonpublic engagement metrics for the Tweet at the time of the request. */ promoted_metrics?: { /** * Format: int32 * @description Number of times this Tweet has been viewed. */ impression_count?: number; /** * Format: int32 * @description Number of times this Tweet has been liked. */ like_count?: number; /** * Format: int32 * @description Number of times this Tweet has been replied to. */ reply_count?: number; /** * Format: int32 * @description Number of times this Tweet has been Retweeted. */ retweet_count?: number; }; /** @description Organic nonpublic engagement metrics for the Tweet at the time of the request. */ organic_metrics?: { /** @description Number of times this Tweet has been viewed. */ impression_count: number; /** @description Number of times this Tweet has been Retweeted. */ retweet_count: number; /** @description Number of times this Tweet has been replied to. */ reply_count: number; /** @description Number of times this Tweet has been liked. */ like_count: number; }; }; /** * @description The Twitter User object * @example [object Object] */ User: { id: components["schemas"]["UserID"]; /** * Format: date-time * @description Creation time of this user. */ created_at?: string; /** @description The friendly name of this user, as shown on their profile. */ name: string; username: components["schemas"]["UserName"]; /** @description Indicates if this user has chosen to protect their Tweets (in other words, if this user's Tweets are private). */ protected?: boolean; /** @description Indicate if this user is a verified Twitter User. */ verified?: boolean; withheld?: components["schemas"]["UserWithheld"]; /** * Format: uri * @description The URL to the profile image for this user. */ profile_image_url?: string; /** @description The location specified in the user's profile, if the user provided one. As this is a freeform value, it may not indicate a valid location, but it may be fuzzily evaluated when performing searches with location queries. */ location?: string; /** @description The URL specified in the user's profile. */ url?: string; /** @description The text of this user's profile description (also known as bio), if the user provided one. */ description?: string; /** @description A list of metadata found in the user's profile description. */ entities?: { /** @description Expanded details for the URL specified in the user's profile, with start and end indices. */ url?: { urls?: components["schemas"]["UrlEntity"][]; }; description?: components["schemas"]["FullTextEntities"]; }; pinned_tweet_id?: components["schemas"]["TweetID"]; /** @description A list of metrics for this user */ public_metrics?: { /** @description Number of users who are following this user. */ followers_count: number; /** @description Number of users this user is following. */ following_count: number; /** @description The number of Tweets (including Retweets) posted by this user. */ tweet_count: number; /** @description The number of lists that include this user. */ listed_count: number; }; }; /** @description The Twitter handle (screen name) of this user. */ UserName: string; MultiUserLookupResponse: { data?: components["schemas"]["User"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; }; SingleUserLookupResponse: { data?: components["schemas"]["User"]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; }; MultiTweetLookupResponse: { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; meta?: { /** @description The number of spaces results returned in this response */ result_count?: number; }; errors?: components["schemas"]["Problem"][]; }; QuoteTweetLookupResponse: { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; meta?: { /** @description This value is used to get the next 'page' of results by providing it to the pagination_token parameter. */ next_token?: string; /** @description The number of quoting tweets returned in this response */ result_count?: number; }; errors?: components["schemas"]["Problem"][]; }; SingleTweetLookupResponse: { data?: components["schemas"]["Tweet"]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; }; /** @description A [GeoJson Point](https://tools.ietf.org/html/rfc7946#section-3.1.2) geometry object. */ Point: { /** * @example Point * @enum {string} */ type: "Point"; coordinates: components["schemas"]["Position"]; }; /** * @description A [GeoJson Position](https://tools.ietf.org/html/rfc7946#section-3.1.1) in the format `[longitude,latitude]`. * @example -105.18816086351444,40.247749999999996 */ Position: number[]; Geo: { /** @enum {string} */ type: "Feature"; /** @example -105.193475,39.60973,-105.053164,39.761974 */ bbox: number[]; geometry?: components["schemas"]["Point"]; properties: { [key: string]: unknown }; }; /** * @description The identifier for this place * @example f7eb2fa2fea288b1 */ PlaceId: string; Place: { id: components["schemas"]["PlaceId"]; /** * @description The human readable name of this place. * @example Lakewood */ name?: string; country_code?: components["schemas"]["CountryCode"]; place_type?: components["schemas"]["PlaceType"]; /** * @description The full name of this place. * @example Lakewood, CO */ full_name: string; /** * @description The full name of the county in which this place exists. * @example United States */ country?: string; contained_within?: components["schemas"]["PlaceId"][]; geo?: components["schemas"]["Geo"]; }; /** * @example city * @enum {string} */ PlaceType: | "poi" | "neighborhood" | "city" | "admin" | "country" | "unknown"; /** @description Represent a Poll attached to a Tweet */ Poll: { id: components["schemas"]["PollId"]; options: components["schemas"]["PollOption"][]; /** @enum {string} */ voting_status?: "open" | "closed"; /** Format: date-time */ end_datetime?: string; duration_minutes?: number; }; /** * @description Unique identifier of this poll. * @example 1365059861688410112 */ PollId: string; /** @description Describes a choice in a Poll object. */ PollOption: { /** @description Position of this choice in the poll. */ position: number; label: components["schemas"]["PollOptionLabel"]; /** @description Number of users who voted for this choice. */ votes: number; }; /** @description The text of a poll choice. */ PollOptionLabel: string; /** * Format: int32 * @description Duration of the poll in minutes. */ DurationMinutes: number; /** @description A Twitter List is a curated group of accounts. */ List: { id: components["schemas"]["ListID"]; /** @description The name of this List. */ name: string; /** Format: date-time */ created_at?: string; description?: string; follower_count?: number; member_count?: number; owner_id?: components["schemas"]["UserID"]; private?: boolean; }; /** * @description The unique identifier of this List. * @example 1146654567674912769 */ ListID: string; ListCreateRequest: { name: string; description?: string; private?: boolean; }; ListCreateResponse: { data?: components["schemas"]["List"]; errors?: components["schemas"]["Problem"][]; }; ListDeleteResponse: { data?: { deleted?: boolean; }; errors?: components["schemas"]["Problem"][]; }; ListUpdateRequest: { name?: string; description?: string; private?: boolean; }; ListUpdateResponse: { data?: { updated?: boolean; }; errors?: components["schemas"]["Problem"][]; }; ListAddMemberRequest: { user_id?: components["schemas"]["UserID"]; }; ListMemberResponse: { data?: { is_member?: boolean; }; errors?: components["schemas"]["Problem"][]; }; ListFollowRequest: { list_id?: components["schemas"]["ListID"]; }; ListFollowedResponse: { data?: { following?: boolean; }; errors?: components["schemas"]["Problem"][]; }; ListPinRequest: { list_id?: components["schemas"]["ListID"]; }; ListPinnedResponse: { data?: { pinned?: boolean; }; errors?: components["schemas"]["Problem"][]; }; SingleListLookupResponse: { data?: components["schemas"]["List"]; includes?: { users?: components["schemas"]["User"][]; }; errors?: components["schemas"]["Problem"][]; }; MultiListResponse: { data?: components["schemas"]["List"][]; includes?: { users?: components["schemas"]["User"][]; }; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** @description The number of list results returned in this response */ result_count?: number; }; errors?: components["schemas"]["Problem"][]; }; MultiListNoPaginationResponse: { data?: components["schemas"]["List"][]; meta?: { /** @description The number of list results returned in this response */ result_count?: number; }; errors?: components["schemas"]["Problem"][]; }; AddBookmarkRequest: { tweet_id: components["schemas"]["TweetID"]; }; BookmarkMutationResponse: { data?: { bookmarked?: boolean; }; errors?: components["schemas"]["Problem"][]; }; TweetDeleteResponse: { data?: { deleted: boolean; }; errors?: components["schemas"]["Problem"][]; }; TweetCreateResponse: { data?: { id: components["schemas"]["TweetID"]; text: components["schemas"]["TweetText"]; }; errors?: components["schemas"]["Problem"][]; }; Media: { type: string; media_key?: components["schemas"]["MediaKey"]; height?: components["schemas"]["MediaHeight"]; width?: components["schemas"]["MediaWidth"]; }; /** * @description The unique identifier of this Media. * @example 1146654567674912769 */ MediaId: string; Photo: components["schemas"]["Media"] & { /** Format: uri */ url?: string; alt_text?: string; }; Video: components["schemas"]["Media"] & { /** Format: uri */ preview_image_url?: string; duration_ms?: number; /** @description An array of all available variants of the media */ variants?: { /** @description The bit rate of the media */ bit_rate?: number; /** @description The content type of the media */ content_type?: string; /** * Format: uri * @description The url to the media */ url?: string; }[]; /** @description Engagement metrics for the Media at the time of the request. */ public_metrics?: { /** * Format: int32 * @description Number of times this video has been viewed. */ view_count?: number; }; /** @description Nonpublic engagement metrics for the Media at the time of the request. */ non_public_metrics?: { /** * Format: int32 * @description Number of users who made it through 0% of the video. */ playback_0_count?: number; /** * Format: int32 * @description Number of users who made it through 25% of the video. */ playback_25_count?: number; /** * Format: int32 * @description Number of users who made it through 50% of the video. */ playback_50_count?: number; /** * Format: int32 * @description Number of users who made it through 75% of the video. */ playback_75_count?: number; /** * Format: int32 * @description Number of users who made it through 100% of the video. */ playback_100_count?: number; }; /** @description Organic nonpublic engagement metrics for the Media at the time of the request. */ organic_metrics?: { /** * Format: int32 * @description Number of users who made it through 0% of the video. */ playback_0_count?: number; /** * Format: int32 * @description Number of users who made it through 25% of the video. */ playback_25_count?: number; /** * Format: int32 * @description Number of users who made it through 50% of the video. */ playback_50_count?: number; /** * Format: int32 * @description Number of users who made it through 75% of the video. */ playback_75_count?: number; /** * Format: int32 * @description Number of users who made it through 100% of the video. */ playback_100_count?: number; /** * Format: int32 * @description Number of times this video has been viewed. */ view_count?: number; }; /** @description Promoted nonpublic engagement metrics for the Media at the time of the request. */ promoted_metrics?: { /** * Format: int32 * @description Number of users who made it through 0% of the video. */ playback_0_count?: number; /** * Format: int32 * @description Number of users who made it through 25% of the video. */ playback_25_count?: number; /** * Format: int32 * @description Number of users who made it through 50% of the video. */ playback_50_count?: number; /** * Format: int32 * @description Number of users who made it through 75% of the video. */ playback_75_count?: number; /** * Format: int32 * @description Number of users who made it through 100% of the video. */ playback_100_count?: number; /** * Format: int32 * @description Number of times this video has been viewed. */ view_count?: number; }; }; AnimatedGif: components["schemas"]["Media"] & { /** Format: uri */ preview_image_url?: string; /** @description An array of all available variants of the media */ variants?: { /** @description The bit rate of the media */ bit_rate?: number; /** @description The content type of the media */ content_type?: string; /** * Format: uri * @description The url to the media */ url?: string; }[]; }; /** @description The Media Key identifier for this attachment. */ MediaKey: string; /** @description Indicates withholding details for [withheld content](https://help.twitter.com/en/rules-and-policies/tweet-withheld-by-country). */ TweetWithheld: { /** @description Indicates if the content is being withheld for on the basis of copyright infringement. */ copyright: boolean; /** @description Provides a list of countries where this content is not available. */ country_codes: components["schemas"]["CountryCode"][]; /** * @description Indicates whether the content being withheld is the `tweet` or a `user`. * @enum {string} */ scope?: "tweet" | "user"; }; /** @description Indicates withholding details for [withheld content](https://help.twitter.com/en/rules-and-policies/tweet-withheld-by-country). */ UserWithheld: { /** @description Provides a list of countries where this content is not available. */ country_codes: components["schemas"]["CountryCode"][]; /** * @description Indicates that the content being withheld is a `user`. * @enum {string} */ scope?: "user"; }; /** * @description A two-letter ISO 3166-1 alpha-2 country code * @example US */ CountryCode: string; /** @description A generic problem with no additional information beyond that provided by the HTTP status code. */ GenericProblem: components["schemas"]["Problem"]; /** @description A problem that indicates this request is invalid. */ InvalidRequestProblem: components["schemas"]["Problem"] & { errors?: { parameters?: { [key: string]: string[] }; message?: string; }[]; }; /** @description A problem that indicates that a given Tweet, User, etc. does not exist. */ ResourceNotFoundProblem: components["schemas"]["Problem"] & { parameter: string; /** @description Value will match the schema of the field. */ value: unknown; resource_id: string; /** @enum {string} */ resource_type: "user" | "tweet" | "media" | "list" | "space"; }; /** @description A problem that indicates you are not allowed to see a particular Tweet, User, etc. */ ResourceUnauthorizedProblem: components["schemas"]["Problem"] & { value: string; parameter: string; /** @enum {string} */ section: "data" | "includes"; resource_id: string; /** @enum {string} */ resource_type: "tweet" | "user" | "media" | "list" | "space"; }; /** @description A problem that indicates a particular Tweet, User, etc. is not available to you. */ ResourceUnavailableProblem: components["schemas"]["Problem"] & { parameter: string; resource_id: string; /** @enum {string} */ resource_type: "user" | "tweet" | "media" | "list" | "space"; }; /** @description A problem that indicates that you are not allowed to see a particular field on a Tweet, User, etc. */ FieldUnauthorizedProblem: components["schemas"]["Problem"] & { /** @enum {string} */ section: "data" | "includes"; /** @enum {string} */ resource_type: "tweet" | "user" | "media" | "list" | "space"; field: string; }; /** @description A problem that indicates your client is forbidden from making this request. */ ClientForbiddenProblem: components["schemas"]["Problem"] & { /** @enum {string} */ reason?: "official-client-forbidden" | "client-not-enrolled"; /** Format: uri */ registration_url?: string; }; /** @description A problem that indicates that the resource requested violates the precepts of this API. */ DisallowedResourceProblem: components["schemas"]["Problem"] & { resource_id: string; /** @enum {string} */ resource_type: "tweet" | "user" | "media" | "list" | "space"; /** @enum {string} */ section: "data" | "includes"; }; /** @description A problem that indicates that the authentication used is not supported. */ UnsupportedAuthenticationProblem: components["schemas"]["Problem"]; /** @description A problem that indicates that a usage cap has been exceeded. */ UsageCapExceededProblem: components["schemas"]["Problem"] & { /** @enum {string} */ period?: "Daily" | "Monthly"; /** @enum {string} */ scope?: "Account" | "Product"; }; /** @description A problem that indicates something is wrong with the connection */ ConnectionExceptionProblem: components["schemas"]["Problem"] & { /** @enum {string} */ connection_issue?: | "TooManyConnections" | "ProvisioningSubscription" | "RuleConfigurationIssue" | "RulesInvalidIssue"; }; /** @description Your client has gone away. */ ClientDisconnectedProblem: components["schemas"]["Problem"]; /** @description You have been disconnected for operational reasons. */ OperationalDisconnectProblem: components["schemas"]["Problem"] & { /** @enum {string} */ disconnect_type?: | "OperationalDisconnect" | "UpstreamOperationalDisconnect" | "ForceDisconnect" | "UpstreamUncleanDisconnect" | "SlowReader" | "InternalError" | "ClientApplicationStateDegraded" | "InvalidRules"; }; /** @description You have exceeded the maximum number of rules. */ RulesCapProblem: components["schemas"]["Problem"]; /** @description The rule you have submitted is invalid. */ InvalidRuleProblem: components["schemas"]["Problem"]; /** @description The rule you have submitted is a duplicate. */ DuplicateRuleProblem: components["schemas"]["Problem"] & { value?: string; id?: string; }; /** @description You cannot create a new job if one is already in progress. */ ConflictProblem: components["schemas"]["Problem"]; /** @description A problem that indicates the user's rule set is not compliant. */ NonCompliantRulesProblem: components["schemas"]["Problem"]; /** @description An HTTP Problem Details object, as defined in IETF RFC 7807 (https://tools.ietf.org/html/rfc7807). */ Problem: { type: string; title: string; detail?: string; status?: number; }; /** @description Represents the response in case of throwing an exception. Mainly for the openapi-generator */ ProblemOrError: | components["schemas"]["Error"] | components["schemas"]["Problem"]; TweetSearchResponse: { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description Most recent Tweet Id returned by search query */ newest_id?: string; /** @description Oldest Tweet Id returned by search query */ oldest_id?: string; /** @description This value is used to get the next 'page' of results by providing it to the next_token parameter. */ next_token?: string; /** * Format: int32 * @description Number of search query results */ result_count?: number; }; }; StreamingTweet: { data?: components["schemas"]["Tweet"]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; }; /** @description A tweet or error that can be returned by the streaming tweet API */ FilteredStreamingTweet: | { data: components["schemas"]["Tweet"]; /** @description The list of rules which matched the tweet */ matching_rules: { id: components["schemas"]["RuleId"]; /** @description The user-supplied tag assigned to the rule which matched */ tag?: string; }[]; includes?: components["schemas"]["Expansions"]; } | { errors: components["schemas"]["Problem"][]; }; /** * @description Unique identifier of this rule. * @example 120897978112909812 */ RuleId: string; /** @description A user-provided stream filtering rule. */ Rule: { value: components["schemas"]["RuleValue"]; tag?: components["schemas"]["RuleTag"]; id?: components["schemas"]["RuleId"]; }; /** @description A user-provided stream filtering rule. */ RuleNoId: { value: components["schemas"]["RuleValue"]; tag?: components["schemas"]["RuleTag"]; }; /** * @description A tag meant for the labeling of user provided rules. * @example Non-retweeted coffee tweets */ RuleTag: string; /** * @description The filterlang value of the rule. * @example coffee -is:retweet */ RuleValue: string; RulesResponseMetadata: { sent: string; summary?: components["schemas"]["RulesRequestSummary"]; /** @description This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ next_token?: string; /** * Format: int32 * @description Number of Rules in result set */ result_count?: number; }; RulesRequestSummary: | { /** * Format: int32 * @description Number of user-specified stream filtering rules that were created. * @example 1 */ created: number; /** * Format: int32 * @description Number of user-specified stream filtering rules that were not created. * @example 1 */ not_created: number; /** * Format: int32 * @description Number of valid user-specified stream filtering rules. * @example 1 */ valid: number; /** * Format: int32 * @description Number of invalid user-specified stream filtering rules. * @example 1 */ invalid: number; } | { /** * Format: int32 * @description Number of user-specified stream filtering rules that were deleted. */ deleted: number; /** * Format: int32 * @description Number of user-specified stream filtering rules that were not deleted. */ not_deleted: number; }; AddOrDeleteRulesRequest: | components["schemas"]["AddRulesRequest"] | components["schemas"]["DeleteRulesRequest"]; /** @description A response from modifying user-specified stream filtering rules. */ AddOrDeleteRulesResponse: { /** @description All user-specified stream filtering rules that were created. */ data?: components["schemas"]["Rule"][]; meta: components["schemas"]["RulesResponseMetadata"]; errors?: components["schemas"]["Problem"][]; }; /** @description A request to add a user-specified stream filtering rule. */ AddRulesRequest: { add: components["schemas"]["RuleNoId"][]; }; /** @description A response from deleting user-specified stream filtering rules. */ DeleteRulesRequest: { /** @description IDs and values of all deleted user-specified stream filtering rules. */ delete: { /** @description IDs of all deleted user-specified stream filtering rules. */ ids?: components["schemas"]["RuleId"][]; /** @description Values of all deleted user-specified stream filtering rules. */ values?: components["schemas"]["RuleValue"][]; }; }; GenericTweetsTimelineResponse: { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description Newest Tweet ID in the result set */ newest_id?: components["schemas"]["TweetID"]; /** @description Oldest Tweet ID in the result set */ oldest_id?: components["schemas"]["TweetID"]; /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** * Format: int32 * @description Number of Tweets in result set */ result_count?: number; }; }; UsersBlockingMutationResponse: { data?: { blocking?: boolean; }; errors?: components["schemas"]["Problem"][]; }; GenericMultipleUsersLookupResponse: { data?: components["schemas"]["User"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** @description The number of user results returned in this response */ result_count?: number; }; }; ListLookupMultipleUsersLookupResponse: { data?: components["schemas"]["User"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** @description The number of user results returned in this response */ result_count?: number; }; }; UsersMutingMutationResponse: { data?: { muting?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersFollowingLookupResponse: { data?: components["schemas"]["User"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** @description The number of user results returned in this response */ result_count?: number; }; }; UsersFollowingCreateResponse: { data?: { following?: boolean; pending_follow?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersFollowingDeleteResponse: { data?: { following?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersLikesCreateRequest: { tweet_id: string; }; UsersLikesCreateResponse: { data?: { liked?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersLikesDeleteResponse: { data?: { liked?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersRetweetsCreateRequest: { tweet_id: string; }; UsersRetweetsCreateResponse: { data?: { retweeted?: boolean; }; errors?: components["schemas"]["Problem"][]; }; UsersRetweetsDeleteResponse: { data?: { retweeted?: boolean; }; errors?: components["schemas"]["Problem"][]; }; TweetCountsResponse: { data?: components["schemas"]["SearchCount"][]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description This value is used to get the next 'page' of results by providing it to the next_token parameter. */ next_token?: string; /** * Format: int32 * @description Sum of search query count results */ total_tweet_count?: number; }; }; /** @description Represent a Search Count Result */ SearchCount: { end: components["schemas"]["End"]; start: components["schemas"]["Start"]; tweet_count: components["schemas"]["TweetCount"]; }; /** * Format: date-time * @description The start time of the bucket */ Start: string; /** * Format: date-time * @description The end time of the bucket */ End: string; /** @description The count for the bucket */ TweetCount: number; /** * @default hour * @enum {string} */ Granularity: "minute" | "hour" | "day"; /** * @description Compliance Job ID * @example 1372966999991541762 */ JobId: string; /** * Format: date-time * @description Creation time of the compliance job. * @example 2021-01-06T18:40:40.000Z */ CreatedAt: string; /** * Format: uri * @description URL to which the user will upload their tweet or user IDs */ UploadUrl: string; /** * Format: uri * @description URL from which the user will retrieve their compliance results */ DownloadUrl: string; /** * Format: date-time * @description Expiration time of the upload URL * @example 2021-01-06T18:40:40.000Z */ UploadExpiration: string; /** * Format: date-time * @description Expiration time of the download URL * @example 2021-01-06T18:40:40.000Z */ DownloadExpiration: string; /** * @description User-provided name for a compliance job * @example my-job */ ComplianceJobName: string; /** * @description Status of a compliance job * @enum {string} */ ComplianceJobStatus: "created" | "in_progress" | "failed" | "complete"; /** * @description Type of compliance job to list. * @enum {string} */ ComplianceJobType: "tweets" | "users"; ComplianceJob: { id: components["schemas"]["JobId"]; type: components["schemas"]["ComplianceJobType"]; created_at: components["schemas"]["CreatedAt"]; upload_url: components["schemas"]["UploadUrl"]; upload_expires_at: components["schemas"]["UploadExpiration"]; download_url: components["schemas"]["DownloadUrl"]; download_expires_at: components["schemas"]["DownloadExpiration"]; name?: components["schemas"]["ComplianceJobName"]; status: components["schemas"]["ComplianceJobStatus"]; }; SingleComplianceJobResponse: { data?: components["schemas"]["ComplianceJob"]; errors?: components["schemas"]["Problem"][]; }; MultiComplianceJobResponse: { data?: components["schemas"]["ComplianceJob"][]; errors?: components["schemas"]["Problem"][]; meta?: { /** * Format: int32 * @description Number of compliance jobs returned */ result_count?: number; }; }; Space: { id: components["schemas"]["SpaceID"]; /** * @description The current state of the space. * @example live * @enum {string} */ state: "live" | "scheduled" | "ended"; /** * Format: date-time * @description When the space was started as a date string * @example 2021-7-14T04:35:55Z */ started_at?: string; /** * @description Denotes if the space is a ticketed space * @example false */ is_ticketed?: boolean; /** * Format: int32 * @description The number of participants in a space * @example 10 */ participant_count?: number; /** * @description The title of the space * @example Spaces are Awesome */ title?: string; /** @description The user ids for the hosts of the space */ host_ids?: components["schemas"]["UserID"][]; /** * Format: date-time * @description When the space was last updated * @example 2021-7-14T04:35:55Z */ updated_at?: string; /** * Format: date-time * @description Creation time of the space * @example 2021-07-06T18:40:40.000Z */ created_at?: string; creator_id?: components["schemas"]["UserID"]; /** * @description The language of the space * @example en */ lang?: string; /** @description An array of user ids for people who were speakers in a space */ speaker_ids?: components["schemas"]["UserID"][]; /** @description An array of user ids for people who were invited to a space */ invited_user_ids?: components["schemas"]["UserID"][]; /** * Format: date-time * @description A date time stamp for when a space is scheduled to begin * @example 2021-07-06T18:40:40.000Z */ scheduled_start?: string; /** * Format: date-time * @description End time of the space * @example 2021-07-06T18:40:40.000Z */ ended_at?: string; /** @description The topics of a space, as selected by its creator */ topics?: { /** @description An ID suitable for use in the REST API. */ id: string; /** @description The description of the given topic. */ description?: string; /** @description The name of the given topic. */ name: string; }[]; /** * Format: int32 * @description The number of people who have either purchased a ticket or set a reminder for this space. * @example 10 */ subscriber_count?: number; }; SingleSpaceLookupResponse: { data?: components["schemas"]["Space"]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; }; MultiSpaceLookupResponse: { data?: components["schemas"]["Space"][]; includes?: components["schemas"]["Expansions"]; meta?: { /** @description The number of spaces results returned in this response */ result_count?: number; }; errors?: components["schemas"]["Problem"][]; }; /** * Format: int32 * @description The number of results to return * @example 25 */ MaxResults: number; }; responses: { /** The request has failed. */ HttpErrorResponse: { content: { "application/json": components["schemas"]["Error"]; "application/problem+json": components["schemas"]["Problem"]; }; }; }; parameters: { /** @description A comma separated list of fields to expand. */ TweetExpansionsParameter: ( | "author_id" | "referenced_tweets.id" | "in_reply_to_user_id" | "geo.place_id" | "attachments.media_keys" | "attachments.poll_ids" | "entities.mentions.username" | "referenced_tweets.id.author_id" )[]; /** @description A comma separated list of Space fields to display. */ SpaceFieldsParameter: ( | "created_at" | "creator_id" | "host_ids" | "invited_user_ids" | "is_ticketed" | "lang" | "participant_count" | "scheduled_start" | "speaker_ids" | "started_at" | "title" | "updated_at" )[]; /** @description A comma separated list of fields to expand. */ UserExpansionsParameter: "pinned_tweet_id"[]; /** @description A comma separated list of fields to expand. */ SpaceExpansionsParameter: ( | "creator_id" | "host_ids" | "invited_user_ids" | "speaker_ids" )[]; /** @description A comma separated list of fields to expand. */ ListExpansionsParameter: "owner_id"[]; /** @description A comma separated list of Tweet fields to display. */ TweetFieldsParameter: ( | "id" | "created_at" | "text" | "author_id" | "in_reply_to_user_id" | "referenced_tweets" | "attachments" | "withheld" | "geo" | "entities" | "public_metrics" | "possibly_sensitive" | "source" | "lang" | "context_annotations" | "non_public_metrics" | "promoted_metrics" | "organic_metrics" | "conversation_id" | "reply_settings" )[]; /** @description A comma separated list of User fields to display. */ UserFieldsParameter: ( | "id" | "created_at" | "name" | "username" | "protected" | "verified" | "withheld" | "profile_image_url" | "location" | "url" | "description" | "entities" | "pinned_tweet_id" | "public_metrics" )[]; /** @description A comma separated list of Media fields to display. */ MediaFieldsParameter: ( | "media_key" | "duration_ms" | "height" | "preview_image_url" | "type" | "url" | "width" | "public_metrics" | "non_public_metrics" | "organic_metrics" | "promoted_metrics" | "alt_text" | "variants" )[]; /** @description A comma separated list of Place fields to display. */ PlaceFieldsParameter: ( | "id" | "name" | "country_code" | "place_type" | "full_name" | "country" | "contained_within" | "geo" )[]; /** @description A comma separated list of Poll fields to display. */ PollFieldsParameter: ( | "id" | "options" | "voting_status" | "end_datetime" | "duration_minutes" )[]; /** @description A comma separated list of List fields to display. */ ListFieldsParameter: ( | "created_at" | "description" | "follower_count" | "id" | "member_count" | "name" | "owner_id" | "private" )[]; /** * @description The minimum Tweet ID to be included in the result set. This parameter takes precedence over start_time if both are specified. * @example 791775337160081409 */ SinceIdRequestParameter: components["schemas"]["TweetID"]; /** * @description The maximum Tweet ID to be included in the result set. This parameter takes precedence over end_time if both are specified. * @example 1346889436626259968 */ UntilIdRequestParameter: components["schemas"]["TweetID"]; /** @description This parameter is used to get the next 'page' of results. */ PaginationTokenRequestParameter: string; /** @description This parameter is used to get a specified 'page' of results. */ SignedLongPaginationTokenRequestParameter: number; /** @description The maximum number of results */ MaxResultsRequestParameter: number; /** @description The maximum number of results */ DefaultMaxResultsRequestParameter: number; /** * @description YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweets will be provided. The since_id parameter takes precedence if it is also specified. * @example 2021-02-01T18:40:40.000Z */ StartTimeRequestParameter: string; /** * @description YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. The until_id parameter takes precedence if it is also specified. * @example 2021-02-14T18:40:40.000Z */ EndTimeRequestParameter: string; /** @description The set of entities to exclude (e.g. 'replies' or 'retweets') */ TweetTypeExcludesRequestParameter: ("replies" | "retweets")[]; /** @description The number of minutes of backfill requested */ BackfillMinutesRequestParameter: number; }; } export interface operations { /** This endpoint returns information about users. Specify users by their ID. */ findUsersById: { parameters: { query: { /** Required. A list of User IDs, comma-separated. You can specify up to 100 IDs. */ ids: components["schemas"]["UserID"][]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** This endpoint returns information about a user. Specify user by ID. */ findUserById: { parameters: { path: { /** Required. A User ID. */ id: components["schemas"]["UserID"]; }; query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** This endpoint returns information about users. Specify users by their username. */ findUsersByUsername: { parameters: { query: { /** Required . A list of usernames, comma-separated. You can specify up to 100 usernames. */ usernames: components["schemas"]["UserName"][]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** This endpoint returns information about the requesting user. */ findMyUser: { parameters: { query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** This endpoint returns information about a user. Specify user by username. */ findUserByUsername: { parameters: { path: { /** Required. A username. */ username: components["schemas"]["UserName"]; }; query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that are blocked by the provided user ID */ usersIdBlocking: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This value is populated by passing the 'next_token' or 'previous_token' returned in a request to paginate through results. */ pagination_token?: string; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user (in the path) to block the target user. The user (in the path) must match the user context authorizing the request */ usersIdBlock: { parameters: { path: { /** The ID of the user that is requesting to block the target user */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersBlockingMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { target_user_id: string; }; }; }; }; /** Causes the source user to unblock the target user. The source user must match the user context authorizing the request */ usersIdUnblock: { parameters: { path: { /** The ID of the user that is requesting to unblock the target user */ source_user_id: components["schemas"]["UserID"]; /** The ID of the user that the source user is requesting to unblock */ target_user_id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersBlockingMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Tweet objects that have been bookmarked by the requesting user */ getUsersIdBookmarks: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: components["parameters"]["MaxResultsRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericTweetsTimelineResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Adds a Tweet (ID in the body) to the requesting user's (in the path) bookmarks */ postUsersIdBookmarks: { parameters: { path: { /** The ID of the user for whom to add bookmarks */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["BookmarkMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["AddBookmarkRequest"]; }; }; }; /** Removes a Tweet from the requesting user's bookmarked Tweets. */ usersIdBookmarksDelete: { parameters: { path: { /** The ID of the user whose bookmark is to be removed. */ id: components["schemas"]["UserID"]; /** The ID of the tweet that the user is removing from bookmarks */ tweet_id: components["schemas"]["TweetID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["BookmarkMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the source user to unmute the target user. The source user must match the user context authorizing the request */ usersIdUnmute: { parameters: { path: { /** The ID of the user that is requesting to unmute the target user */ source_user_id: components["schemas"]["UserID"]; /** The ID of the user that the source user is requesting to unmute */ target_user_id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersMutingMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that are muted by the provided user ID */ usersIdMuting: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user (in the path) to mute the target user. The user (in the path) must match the user context authorizing the request */ usersIdMute: { parameters: { path: { /** The ID of the user that is requesting to mute the target user */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersMutingMutationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { target_user_id: string; }; }; }; }; /** Returns a list of users that follow the provided user ID */ usersIdFollowers: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This value is populated by passing the 'next_token' or 'previous_token' returned in a request to paginate through results. */ pagination_token?: string; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that are being followed by the provided user ID */ usersIdFollowing: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This value is populated by passing the 'next_token' or 'previous_token' returned in a request to paginate through results. */ pagination_token?: string; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersFollowingLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user(in the path) to follow, or “request to follow” for protected users, the target user. The user(in the path) must match the user context authorizing the request */ usersIdFollow: { parameters: { path: { /** The ID of the user that is requesting to follow the target user */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersFollowingCreateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { target_user_id: string; }; }; }; }; /** Causes the source user to unfollow the target user. The source user must match the user context authorizing the request */ usersIdUnfollow: { parameters: { path: { /** The ID of the user that is requesting to unfollow the target user */ source_user_id: components["schemas"]["UserID"]; /** The ID of the user that the source user is requesting to unfollow */ target_user_id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersFollowingDeleteResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a user's followed Lists. */ userFollowedLists: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get a specified 'page' of results. */ pagination_token?: components["parameters"]["SignedLongPaginationTokenRequestParameter"]; /** A comma separated list of List fields to display. */ "list.fields"?: components["parameters"]["ListFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["ListExpansionsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiListResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes a user to follow a List. */ listUserFollow: { parameters: { path: { /** The ID of the authenticated source user that will follow the List */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListFollowedResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["ListFollowRequest"]; }; }; }; /** Causes a user to unfollow a List. */ listUserUnfollow: { parameters: { path: { /** The ID of the authenticated source user that will unfollow the List */ id: components["schemas"]["UserID"]; /** The ID of the List to unfollow */ list_id: components["schemas"]["ListID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListFollowedResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Get a User's List Memberships. */ getUserListMemberships: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get a specified 'page' of results. */ pagination_token?: components["parameters"]["SignedLongPaginationTokenRequestParameter"]; /** A comma separated list of List fields to display. */ "list.fields"?: components["parameters"]["ListFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["ListExpansionsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiListResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Get a User's Owned Lists. */ listUserOwnedLists: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get a specified 'page' of results. */ pagination_token?: components["parameters"]["SignedLongPaginationTokenRequestParameter"]; /** A comma separated list of List fields to display. */ "list.fields"?: components["parameters"]["ListFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["ListExpansionsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiListResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Get a User's Pinned Lists. */ listUserPinnedLists: { parameters: { path: { /** The ID of the user for whom to return results */ id: components["schemas"]["UserID"]; }; query: { /** A comma separated list of List fields to display. */ "list.fields"?: components["parameters"]["ListFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["ListExpansionsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiListNoPaginationResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes a user to pin a List. */ listUserPin: { parameters: { path: { /** The ID of the authenticated source user that will pin the List */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListPinnedResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["ListPinRequest"]; }; }; }; /** Causes a user to remove a pinned List. */ listUserUnpin: { parameters: { path: { /** The ID of the authenticated source user that will remove the pinned List */ id: components["schemas"]["UserID"]; /** The ID of the List to unpin */ list_id: components["schemas"]["ListID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListPinnedResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a variety of information about the Tweet specified by the requested ID. */ findTweetsById: { parameters: { query: { /** A comma separated list of Tweet IDs. Up to 100 are allowed in a single request. */ ids: components["schemas"]["TweetID"][]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiTweetLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user to create a tweet under the authorized account. */ createTweet: { parameters: {}; responses: { /** The request was successful */ 201: { content: { "application/json": components["schemas"]["TweetCreateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { text?: components["schemas"]["TweetText"]; /** @description Link to take the conversation from the public timeline to a private Direct Message. */ direct_message_deep_link?: string; /** @description Link to the Tweet being quoted. This is mutually exclusive from Poll and Media. */ quote_tweet_id?: components["schemas"]["TweetID"]; /** @description Exclusive Tweet for super followers. */ for_super_followers_only?: boolean; /** @description Tweet information of the Tweet being replied to. */ reply?: { in_reply_to_tweet_id?: components["schemas"]["TweetID"]; /** @description A list of User Ids to be excluded from the reply Tweet. */ exclude_reply_user_ids?: components["schemas"]["UserID"][]; }; /** @description Media information being attached to created Tweet. This is mutually exclusive from Quote Tweet Id and Poll. */ media?: { /** @description A list of Media Ids to be attached to a created Tweet. */ media_ids?: components["schemas"]["MediaId"][]; /** @description A list of User Ids to be tagged in the media for created Tweet. */ tagged_user_ids?: components["schemas"]["UserID"][]; }; /** @description Poll options for a Tweet with a poll. This is mutually exclusive from Media and Quote Tweet Id. */ poll?: { options?: components["schemas"]["PollOptionLabel"][]; duration_minutes?: components["schemas"]["DurationMinutes"]; }; /** * @description Settings to indicate who can reply to the Tweet. * @enum {string} */ reply_settings?: "following" | "mentionedUsers"; /** @description Place ID being attached to the Tweet for geo location. */ geo?: { place_id?: string; }; }; }; }; }; /** Returns a variety of information about the Tweet specified by the requested ID. */ findTweetById: { parameters: { path: { /** A single Tweet ID. */ id: components["schemas"]["TweetID"]; }; query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleTweetLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Delete specified Tweet (in the path) by ID. */ deleteTweetById: { parameters: { path: { /** The ID of the Tweet to be deleted. */ id: components["schemas"]["TweetID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["TweetDeleteResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a variety of information about each tweet that quotes the Tweet specified by the requested ID. */ findTweetsThatQuoteATweet: { parameters: { path: { /** The ID of the Quoted Tweet. */ id: components["schemas"]["TweetID"]; }; query: { /** The maximum number of results to be returned. */ max_results?: number; /** The set of entities to exclude (e.g. 'replies' or 'retweets') */ exclude?: components["parameters"]["TweetTypeExcludesRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["QuoteTweetLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Hides or unhides a reply to an owned conversation. */ hideReplyById: { parameters: { path: { /** The ID of the reply that you want to hide or unhide. */ id: components["schemas"]["TweetID"]; }; }; responses: { /** A successful response. The reply has been hidden or unhidden. */ 200: { content: { "application/json": { data?: { hidden?: boolean; }; }; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { hidden?: boolean; }; }; }; }; /** Returns Tweets from the last 7 days that match a search query. */ tweetsRecentSearch: { parameters: { query: { /** One query/rule/filter for matching Tweets. Refer to https:\/\/t.co\/rulelength to identify the max query length */ query: string; /** YYYY-MM-DDTHH:mm:ssZ. The oldest UTC timestamp (from most recent 7 days) from which the Tweets will be provided. Timestamp is in second granularity and is inclusive (i.e. 12:00:01 includes the first second of the minute). */ start_time?: string; /** YYYY-MM-DDTHH:mm:ssZ. The newest, most recent UTC timestamp to which the Tweets will be provided. Timestamp is in second granularity and is exclusive (i.e. 12:00:01 excludes the first second of the minute). */ end_time?: string; /** Returns results with a Tweet ID greater than (that is, more recent than) the specified ID. */ since_id?: components["schemas"]["TweetID"]; /** Returns results with a Tweet ID less than (that is, older than) the specified ID. */ until_id?: components["schemas"]["TweetID"]; /** The maximum number of search results to be returned by a request. */ max_results?: number; /** This order in which to return results. */ sort_order?: "recency" | "relevancy"; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ next_token?: string; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ pagination_token?: string; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** Tweets recent search response */ 200: { content: { "application/json": components["schemas"]["TweetSearchResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Tweets that match a search query. */ tweetsFullarchiveSearch: { parameters: { query: { /** One query/rule/filter for matching Tweets. Refer to https:\/\/t.co\/rulelength to identify the max query length */ query: string; /** YYYY-MM-DDTHH:mm:ssZ. The oldest UTC timestamp from which the Tweets will be provided. Timestamp is in second granularity and is inclusive (i.e. 12:00:01 includes the first second of the minute). */ start_time?: string; /** YYYY-MM-DDTHH:mm:ssZ. The newest, most recent UTC timestamp to which the Tweets will be provided. Timestamp is in second granularity and is exclusive (i.e. 12:00:01 excludes the first second of the minute). */ end_time?: string; /** Returns results with a Tweet ID greater than (that is, more recent than) the specified ID. */ since_id?: components["schemas"]["TweetID"]; /** Returns results with a Tweet ID less than (that is, older than) the specified ID. */ until_id?: components["schemas"]["TweetID"]; /** The maximum number of search results to be returned by a request. */ max_results?: number; /** This order in which to return results. */ sort_order?: "recency" | "relevancy"; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ next_token?: string; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ pagination_token?: string; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** Tweets full archive search response */ 200: { content: { "application/json": components["schemas"]["TweetSearchResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Streams Tweets matching the stream's active rule set. */ searchStream: { parameters: { query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; /** The number of minutes of backfill requested */ backfill_minutes?: components["parameters"]["BackfillMinutesRequestParameter"]; }; }; responses: { /** The request was successful. Successful responses will return a stream of individual JSON Tweet payloads. */ 200: { content: { "application/json": components["schemas"]["FilteredStreamingTweet"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns rules from a user's active rule set. Users can fetch all of their rules or a subset, specified by the provided rule ids. */ getRules: { parameters: { query: { /** A comma-separated list of Rule IDs. */ ids?: components["schemas"]["RuleId"][]; /** The maximum number of results */ max_results?: number; /** This value is populated by passing the 'next_token' returned in a request to paginate through results. */ pagination_token?: string; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": { data: components["schemas"]["Rule"][]; meta: components["schemas"]["RulesResponseMetadata"]; }; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Add or delete rules from a user's active rule set. Users can provide unique, optionally tagged rules to add. Users can delete their entire rule set or a subset specified by rule ids or values. */ addOrDeleteRules: { parameters: { query: { /** Dry Run can be used with both the add and delete action, with the expected result given, but without actually taking any action in the system (meaning the end state will always be as it was when the request was submitted). This is particularly useful to validate rule changes. */ dry_run?: boolean; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["AddOrDeleteRulesResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["AddOrDeleteRulesRequest"]; }; }; }; /** Streams a deterministic 1% of public Tweets. */ sampleStream: { parameters: { query: { /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; /** The number of minutes of backfill requested */ backfill_minutes?: components["parameters"]["BackfillMinutesRequestParameter"]; }; }; responses: { /** The request was successful. Successful responses will return a stream of individual JSON Tweet payloads. */ 200: { content: { "application/json": components["schemas"]["StreamingTweet"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Full open api spec in JSON format. (See https://github.com/OAI/OpenAPI-Specification/blob/master/README.md) */ getOpenApiSpec: { parameters: {}; responses: { /** The request was successful */ 200: { content: { "application/json": { [key: string]: unknown }; }; }; }; }; /** Returns Tweet objects that appears in the provided User ID's home timeline */ usersIdTimeline: { parameters: { path: { /** The ID of the User to list Reverse Chronological Timeline Tweets of */ id: components["schemas"]["UserID"]; }; query: { /** The minimum Tweet ID to be included in the result set. This parameter takes precedence over start_time if both are specified. */ since_id?: components["parameters"]["SinceIdRequestParameter"]; /** The maximum Tweet ID to be included in the result set. This parameter takes precedence over end_time if both are specified. */ until_id?: components["parameters"]["UntilIdRequestParameter"]; /** The maximum number of results */ max_results?: components["parameters"]["MaxResultsRequestParameter"]; /** The set of entities to exclude (e.g. 'replies' or 'retweets') */ exclude?: components["parameters"]["TweetTypeExcludesRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweets will be provided. The since_id parameter takes precedence if it is also specified. */ start_time?: components["parameters"]["StartTimeRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. The until_id parameter takes precedence if it is also specified. */ end_time?: components["parameters"]["EndTimeRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericTweetsTimelineResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of Tweets authored by the provided User ID */ usersIdTweets: { parameters: { path: { /** The ID of the User to list Tweets of */ id: components["schemas"]["UserID"]; }; query: { /** The minimum Tweet ID to be included in the result set. This parameter takes precedence over start_time if both are specified. */ since_id?: components["parameters"]["SinceIdRequestParameter"]; /** The maximum Tweet ID to be included in the result set. This parameter takes precedence over end_time if both are specified. */ until_id?: components["parameters"]["UntilIdRequestParameter"]; /** The maximum number of results */ max_results?: components["parameters"]["MaxResultsRequestParameter"]; /** The set of entities to exclude (e.g. 'replies' or 'retweets') */ exclude?: components["parameters"]["TweetTypeExcludesRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweets will be provided. The since_id parameter takes precedence if it is also specified. */ start_time?: components["parameters"]["StartTimeRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. The until_id parameter takes precedence if it is also specified. */ end_time?: components["parameters"]["EndTimeRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericTweetsTimelineResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Tweet objects that mention username associated to the provided User ID */ usersIdMentions: { parameters: { path: { /** The ID of the User to list mentions of */ id: components["schemas"]["UserID"]; }; query: { /** The minimum Tweet ID to be included in the result set. This parameter takes precedence over start_time if both are specified. */ since_id?: components["parameters"]["SinceIdRequestParameter"]; /** The maximum Tweet ID to be included in the result set. This parameter takes precedence over end_time if both are specified. */ until_id?: components["parameters"]["UntilIdRequestParameter"]; /** The maximum number of results */ max_results?: components["parameters"]["MaxResultsRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweets will be provided. The since_id parameter takes precedence if it is also specified. */ start_time?: components["parameters"]["StartTimeRequestParameter"]; /** YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. The until_id parameter takes precedence if it is also specified. */ end_time?: components["parameters"]["EndTimeRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericTweetsTimelineResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user (in the path) to like the specified tweet. The user in the path must match the user context authorizing the request. */ usersIdLike: { parameters: { path: { /** The ID of the user that is requesting to like the tweet */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersLikesCreateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["UsersLikesCreateRequest"]; }; }; }; /** Causes the user (in the path) to unlike the specified tweet. The user must match the user context authorizing the request */ usersIdUnlike: { parameters: { path: { /** The ID of the user that is requesting to unlike the tweet */ id: components["schemas"]["UserID"]; /** The ID of the tweet that the user is requesting to unlike */ tweet_id: components["schemas"]["TweetID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersLikesDeleteResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of Tweets liked by the provided User ID */ usersIdLikedTweets: { parameters: { path: { /** The ID of the User to list the liked Tweets of */ id: components["schemas"]["UserID"]; }; query: { /** The maximum number of results */ max_results?: components["parameters"]["MaxResultsRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** * Format: int32 * @description Number of Tweets in result set */ result_count?: number; }; }; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that have liked the provided Tweet ID */ tweetsIdLikingUsers: { parameters: { path: { /** The ID of the Tweet for which to return results */ id: components["schemas"]["TweetID"]; }; query: { /** The maximum number of results */ max_results?: components["parameters"]["DefaultMaxResultsRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that have retweeted the provided Tweet ID */ tweetsIdRetweetingUsers: { parameters: { path: { /** The ID of the Tweet for which to return results */ id: components["schemas"]["TweetID"]; }; query: { /** The maximum number of results */ max_results?: components["parameters"]["DefaultMaxResultsRequestParameter"]; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["GenericMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes the user (in the path) to retweet the specified tweet. The user in the path must match the user context authorizing the request. */ usersIdRetweets: { parameters: { path: { /** The ID of the user that is requesting to retweet the tweet */ id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersRetweetsCreateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["UsersRetweetsCreateRequest"]; }; }; }; /** Causes the user (in the path) to unretweet the specified tweet. The user must match the user context authorizing the request */ usersIdUnretweets: { parameters: { path: { /** The ID of the user that is requesting to unretweet the tweet */ id: components["schemas"]["UserID"]; /** The ID of the tweet that the user is requesting to unretweet */ source_tweet_id: components["schemas"]["TweetID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["UsersRetweetsDeleteResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Tweet Counts from the last 7 days that match a search query. */ tweetCountsRecentSearch: { parameters: { query: { /** One query/rule/filter for matching Tweets. Refer to https:\/\/t.co\/rulelength to identify the max query length */ query: string; /** YYYY-MM-DDTHH:mm:ssZ. The oldest UTC timestamp (from most recent 7 days) from which the Tweets will be provided. Timestamp is in second granularity and is inclusive (i.e. 12:00:01 includes the first second of the minute). */ start_time?: string; /** YYYY-MM-DDTHH:mm:ssZ. The newest, most recent UTC timestamp to which the Tweets will be provided. Timestamp is in second granularity and is exclusive (i.e. 12:00:01 excludes the first second of the minute). */ end_time?: string; /** Returns results with a Tweet ID greater than (that is, more recent than) the specified ID. */ since_id?: components["schemas"]["TweetID"]; /** Returns results with a Tweet ID less than (that is, older than) the specified ID. */ until_id?: components["schemas"]["TweetID"]; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ next_token?: string; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ pagination_token?: string; /** The granularity for the search counts results. */ granularity?: components["schemas"]["Granularity"]; }; }; responses: { /** Recent tweet counts response */ 200: { content: { "application/json": components["schemas"]["TweetCountsResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Tweet Counts that match a search query. */ tweetCountsFullArchiveSearch: { parameters: { query: { /** One query/rule/filter for matching Tweets. Refer to https:\/\/t.co\/rulelength to identify the max query length */ query: string; /** YYYY-MM-DDTHH:mm:ssZ. The oldest UTC timestamp (from most recent 7 days) from which the Tweets will be provided. Timestamp is in second granularity and is inclusive (i.e. 12:00:01 includes the first second of the minute). */ start_time?: string; /** YYYY-MM-DDTHH:mm:ssZ. The newest, most recent UTC timestamp to which the Tweets will be provided. Timestamp is in second granularity and is exclusive (i.e. 12:00:01 excludes the first second of the minute). */ end_time?: string; /** Returns results with a Tweet ID greater than (that is, more recent than) the specified ID. */ since_id?: components["schemas"]["TweetID"]; /** Returns results with a Tweet ID less than (that is, older than) the specified ID. */ until_id?: components["schemas"]["TweetID"]; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ next_token?: string; /** This parameter is used to get the next 'page' of results. The value used with the parameter is pulled directly from the response provided by the API, and should not be modified. */ pagination_token?: string; /** The granularity for the search counts results. */ granularity?: components["schemas"]["Granularity"]; }; }; responses: { /** Tweet counts response */ 200: { content: { "application/json": components["schemas"]["TweetCountsResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns recent compliance jobs for a given job type and optional job status */ listBatchComplianceJobs: { parameters: { query: { /** Type of compliance job to list. */ type: components["schemas"]["ComplianceJobType"]; /** Status of compliance job to list. */ status?: components["schemas"]["ComplianceJobStatus"]; }; }; responses: { /** List compliance jobs response */ 200: { content: { "application/json": components["schemas"]["MultiComplianceJobResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Creates a compliance for the given job type */ createBatchComplianceJob: { parameters: {}; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleComplianceJobResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": { type: components["schemas"]["ComplianceJobType"]; /** @description If true, this endpoint will return a pre-signed URL with resumable uploads enabled */ resumable?: boolean; name?: components["schemas"]["ComplianceJobName"]; }; }; }; }; /** Returns a single compliance job by ID */ getBatchComplianceJob: { parameters: { path: { /** ID of the compliance job to retrieve. */ id: components["schemas"]["JobId"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleComplianceJobResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Creates a new List. */ listIdCreate: { parameters: {}; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListCreateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["ListCreateRequest"]; }; }; }; /** Returns a List */ listIdGet: { parameters: { path: { /** The ID of the List to get */ id: components["schemas"]["ListID"]; }; query: { /** A comma separated list of List fields to display. */ "list.fields"?: components["parameters"]["ListFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["ListExpansionsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleListLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Update a List that you own. */ listIdUpdate: { parameters: { path: { /** The ID of the List to modify */ id: components["schemas"]["ListID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListUpdateResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["ListUpdateRequest"]; }; }; }; /** Delete a List that you own. */ listIdDelete: { parameters: { path: { /** The ID of the List to delete */ id: components["schemas"]["ListID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListDeleteResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that follow a List by the provided List ID */ listGetFollowers: { parameters: { path: { /** The ID of the List for which to return followers */ id: components["schemas"]["ListID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get a specified 'page' of results. */ pagination_token?: components["parameters"]["SignedLongPaginationTokenRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListLookupMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of users that are members of a List by the provided List ID */ listGetMembers: { parameters: { path: { /** The ID of the List for which to return members */ id: components["schemas"]["ListID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get a specified 'page' of results. */ pagination_token?: components["parameters"]["SignedLongPaginationTokenRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["UserExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListLookupMultipleUsersLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Causes a user to become a member of a List. */ listAddMember: { parameters: { path: { /** The ID of the List to add a member */ id: components["schemas"]["ListID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListMemberResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; requestBody: { content: { "application/json": components["schemas"]["ListAddMemberRequest"]; }; }; }; /** Causes a user to be removed from the members of a List. */ listRemoveMember: { parameters: { path: { /** The ID of the List to remove a member */ id: components["schemas"]["ListID"]; /** The ID of user that will be removed from the List */ user_id: components["schemas"]["UserID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["ListMemberResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a list of Tweets associated with the provided List ID */ listsIdTweets: { parameters: { path: { /** The ID of the List to list Tweets of */ id: components["schemas"]["ListID"]; }; query: { /** The maximum number of results */ max_results?: number; /** This parameter is used to get the next 'page' of results. */ pagination_token?: components["parameters"]["PaginationTokenRequestParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["TweetExpansionsParameter"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; /** A comma separated list of Media fields to display. */ "media.fields"?: components["parameters"]["MediaFieldsParameter"]; /** A comma separated list of Place fields to display. */ "place.fields"?: components["parameters"]["PlaceFieldsParameter"]; /** A comma separated list of Poll fields to display. */ "poll.fields"?: components["parameters"]["PollFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": { data?: components["schemas"]["Tweet"][]; includes?: components["schemas"]["Expansions"]; errors?: components["schemas"]["Problem"][]; meta?: { /** @description The previous token */ previous_token?: string; /** @description The next token */ next_token?: string; /** * Format: int32 * @description Number of Tweets in result set */ result_count?: number; }; }; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a variety of information about the Space specified by the requested ID */ findSpaceById: { parameters: { path: { /** The space id to be retrieved */ id: components["schemas"]["SpaceID"]; }; query: { /** A comma separated list of Space fields to display. */ "space.fields"?: components["parameters"]["SpaceFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["SpaceExpansionsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["SingleSpaceLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a variety of information about the Spaces specified by the requested IDs */ findSpacesByIds: { parameters: { query: { /** A list of space ids */ ids: components["schemas"]["SpaceID"][]; /** A comma separated list of Space fields to display. */ "space.fields"?: components["parameters"]["SpaceFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["SpaceExpansionsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiSpaceLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns a variety of information about the Spaces created by the provided User IDs */ findSpacesByCreatorIds: { parameters: { query: { /** The users to search through */ user_ids: components["schemas"]["UserID"][]; /** A comma separated list of Space fields to display. */ "space.fields"?: components["parameters"]["SpaceFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["SpaceExpansionsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiSpaceLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Returns Spaces that match the provided query. */ searchSpaces: { parameters: { query: { /** The search query */ query: string; /** The state of spaces to search for */ state?: "live" | "scheduled" | "all"; /** The number of results to return. The maximum for this value is 100. */ max_results?: components["schemas"]["MaxResults"]; /** A comma separated list of Space fields to display. */ "space.fields"?: components["parameters"]["SpaceFieldsParameter"]; /** A comma separated list of fields to expand. */ expansions?: components["parameters"]["SpaceExpansionsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiSpaceLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Retrieves tweets shared in the specified space */ spaceTweets: { parameters: { query: { /** The number of tweets to fetch from the provided space. If not provided, the value will default to the maximum of 100 */ max_results?: components["schemas"]["MaxResults"]; /** A comma separated list of Tweet fields to display. */ "tweet.fields"?: components["parameters"]["TweetFieldsParameter"]; }; path: { /** The space id from which tweets will be retrieved */ id: components["schemas"]["SpaceID"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiTweetLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; /** Retrieves the list of users who purchased a ticket to the given space */ spaceBuyers: { parameters: { path: { /** The space id from which tweets will be retrieved */ id: components["schemas"]["SpaceID"]; }; query: { /** A comma separated list of User fields to display. */ "user.fields"?: components["parameters"]["UserFieldsParameter"]; }; }; responses: { /** The request was successful */ 200: { content: { "application/json": components["schemas"]["MultiUserLookupResponse"]; }; }; default: components["responses"]["HttpErrorResponse"]; }; }; } export interface external {} export type findUsersById = operations['findUsersById'] export type findUserById = operations['findUserById'] export type findUsersByUsername = operations['findUsersByUsername'] export type findMyUser = operations['findMyUser'] export type findUserByUsername = operations['findUserByUsername'] export type usersIdBlock = operations['usersIdBlock'] export type usersIdBlocking = operations['usersIdBlocking'] export type usersIdUnblock = operations['usersIdUnblock'] export type getUsersIdBookmarks = operations['getUsersIdBookmarks'] export type postUsersIdBookmarks = operations['postUsersIdBookmarks'] export type usersIdBookmarksDelete = operations['usersIdBookmarksDelete'] export type usersIdUnmute = operations['usersIdUnmute'] export type usersIdMute = operations['usersIdMute'] export type usersIdMuting = operations['usersIdMuting'] export type usersIdFollowers = operations['usersIdFollowers'] export type usersIdFollowing = operations['usersIdFollowing'] export type usersIdFollow = operations['usersIdFollow'] export type usersIdUnfollow = operations['usersIdUnfollow'] export type userFollowedLists = operations['userFollowedLists'] export type listUserFollow = operations['listUserFollow'] export type listUserUnfollow = operations['listUserUnfollow'] export type getUserListMemberships = operations['getUserListMemberships'] export type listUserOwnedLists = operations['listUserOwnedLists'] export type listUserPinnedLists = operations['listUserPinnedLists'] export type listUserPin = operations['listUserPin'] export type listUserUnpin = operations['listUserUnpin'] export type findTweetsById = operations['findTweetsById'] export type createTweet = operations['createTweet'] export type findTweetById = operations['findTweetById'] export type deleteTweetById = operations['deleteTweetById'] export type findTweetsThatQuoteATweet = operations['findTweetsThatQuoteATweet'] export type hideReplyById = operations['hideReplyById'] export type tweetsRecentSearch = operations['tweetsRecentSearch'] export type tweetsFullarchiveSearch = operations['tweetsFullarchiveSearch'] export type searchStream = operations['searchStream'] export type getRules = operations['getRules'] export type addOrDeleteRules = operations['addOrDeleteRules'] export type sampleStream = operations['sampleStream'] export type getOpenApiSpec = operations['getOpenApiSpec'] export type usersIdTimeline = operations['usersIdTimeline'] export type usersIdTweets = operations['usersIdTweets'] export type usersIdMentions = operations['usersIdMentions'] export type usersIdLike = operations['usersIdLike'] export type usersIdUnlike = operations['usersIdUnlike'] export type usersIdLikedTweets = operations['usersIdLikedTweets'] export type tweetsIdLikingUsers = operations['tweetsIdLikingUsers'] export type tweetsIdRetweetingUsers = operations['tweetsIdRetweetingUsers'] export type usersIdRetweets = operations['usersIdRetweets'] export type usersIdUnretweets = operations['usersIdUnretweets'] export type tweetCountsRecentSearch = operations['tweetCountsRecentSearch'] export type tweetCountsFullArchiveSearch = operations['tweetCountsFullArchiveSearch'] export type listBatchComplianceJobs = operations['listBatchComplianceJobs'] export type createBatchComplianceJob = operations['createBatchComplianceJob'] export type getBatchComplianceJob = operations['getBatchComplianceJob'] export type listIdCreate = operations['listIdCreate'] export type listIdDelete = operations['listIdDelete'] export type listIdUpdate = operations['listIdUpdate'] export type listIdGet = operations['listIdGet'] export type listGetFollowers = operations['listGetFollowers'] export type listAddMember = operations['listAddMember'] export type listGetMembers = operations['listGetMembers'] export type listRemoveMember = operations['listRemoveMember'] export type listsIdTweets = operations['listsIdTweets'] export type findSpaceById = operations['findSpaceById'] export type findSpacesByIds = operations['findSpacesByIds'] export type findSpacesByCreatorIds = operations['findSpacesByCreatorIds'] export type searchSpaces = operations['searchSpaces'] export type spaceTweets = operations['spaceTweets'] export type spaceBuyers = operations['spaceBuyers']
the_stack
import * as sinon from "sinon"; import {Clipper} from "../../../scripts/clipperUI/frontEndGlobals"; import {Status} from "../../../scripts/clipperUI/status"; import {OneNoteApiUtils} from "../../../scripts/clipperUI/oneNoteApiUtils"; import {SectionPicker, SectionPickerClass, SectionPickerState} from "../../../scripts/clipperUI/components/sectionPicker"; import {ClipperStorageKeys} from "../../../scripts/storage/clipperStorageKeys"; import {MithrilUtils} from "../../mithrilUtils"; import {MockProps} from "../../mockProps"; import {TestModule} from "../../testModule"; module TestConstants { export module Ids { export var sectionLocationContainer = "sectionLocationContainer"; export var sectionPickerContainer = "sectionPickerContainer"; } export var defaultUserInfoAsJsonString = JSON.stringify({ emailAddress: "mockEmail@hotmail.com", fullName: "Mock Johnson", accessToken: "mockToken", accessTokenExpiration: 3000 }); } type StoredSection = { section: OneNoteApi.Section, path: string, parentId: string }; // Mock out the Clipper.Storage functionality let mockStorage: { [key: string]: string } = {}; Clipper.getStoredValue = (key: string, callback: (value: string) => void) => { callback(mockStorage[key]); }; Clipper.storeValue = (key: string, value: string) => { mockStorage[key] = value; }; function initializeClipperStorage(notebooks: string, curSection: string, userInfo?: string) { mockStorage = { }; Clipper.storeValue(ClipperStorageKeys.cachedNotebooks, notebooks); Clipper.storeValue(ClipperStorageKeys.currentSelectedSection, curSection); Clipper.storeValue(ClipperStorageKeys.userInformation, userInfo); } function createNotebook(id: string, isDefault?: boolean, sectionGroups?: OneNoteApi.SectionGroup[], sections?: OneNoteApi.Section[]): OneNoteApi.Notebook { return { name: id.toUpperCase(), isDefault: isDefault, userRole: undefined, isShared: true, links: undefined, id: id.toLowerCase(), self: undefined, createdTime: undefined, lastModifiedTime: undefined, createdBy: undefined, lastModifiedBy: undefined, sectionsUrl: undefined, sectionGroupsUrl: undefined, sections: sections, sectionGroups: sectionGroups }; }; function createSectionGroup(id: string, sectionGroups?: OneNoteApi.SectionGroup[], sections?: OneNoteApi.Section[]): OneNoteApi.SectionGroup { return { name: id.toUpperCase(), id: id.toLowerCase(), self: undefined, createdTime: undefined, lastModifiedTime: undefined, createdBy: undefined, lastModifiedBy: undefined, sectionsUrl: undefined, sectionGroupsUrl: undefined, sections: sections, sectionGroups: sectionGroups }; }; function createSection(id: string, isDefault?: boolean): OneNoteApi.Section { return { name: id.toUpperCase(), isDefault: isDefault, parentNotebook: undefined, id: id.toLowerCase(), self: undefined, createdTime: undefined, lastModifiedTime: undefined, createdBy: undefined, lastModifiedBy: undefined, pagesUrl: undefined, pages: undefined }; }; export class SectionPickerTests extends TestModule { private defaultComponent; private mockClipperState = MockProps.getMockClipperState(); protected module() { return "sectionPicker"; } protected beforeEach() { this.defaultComponent = <SectionPicker onPopupToggle={() => {}} clipperState={this.mockClipperState} />; } protected tests() { test("fetchCachedNotebookAndSectionInfoAsState should return the cached notebooks, cached current section, and the succeed status if cached information is found", () => { let clipperState = MockProps.getMockClipperState(); let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "A > B > C", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection)); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => { strictEqual(JSON.stringify(response), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "The cached information should be returned as SectionPickerState"); }); }); test("fetchCachedNotebookAndSectionInfoAsState should return undefined if no cached information is found", () => { let clipperState = MockProps.getMockClipperState(); initializeClipperStorage(undefined, undefined); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => { strictEqual(response, undefined, "The undefined notebooks and section information should be returned as SectionPickerState"); }); }); test("fetchCachedNotebookAndSectionInfoAsState should return the cached notebooks, undefined section, and the succeed status if no cached section is found", () => { let clipperState = MockProps.getMockClipperState(); let mockNotebooks = MockProps.getMockNotebooks(); initializeClipperStorage(JSON.stringify(mockNotebooks), undefined); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => { strictEqual(JSON.stringify(response), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }), "The cached information should be returned as SectionPickerState"); }); }); test("fetchCachedNotebookAndSectionInfoAsState should return undefined when no notebooks are found, even if section information is found", () => { let clipperState = MockProps.getMockClipperState(); let mockSection = { section: MockProps.getMockNotebooks()[0].sections[0], path: "A > B > C", parentId: MockProps.getMockNotebooks()[0].id }; initializeClipperStorage(undefined, JSON.stringify(mockSection)); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => { strictEqual(response, undefined, "The cached information should be returned as SectionPickerState"); }); }); test("convertNotebookListToState should return the notebook list, success status, and default section in the general case", () => { let section = createSection("S", true); let sectionGroup2 = createSectionGroup("SG2", [], [section]); let sectionGroup1 = createSectionGroup("SG1", [sectionGroup2], []); let notebook = createNotebook("N", true, [sectionGroup1], []); let notebooks = [notebook]; let actual = SectionPickerClass.convertNotebookListToState(notebooks); strictEqual(actual.notebooks, notebooks, "The notebooks property is correct"); strictEqual(actual.status, Status.Succeeded, "The status property is correct"); deepEqual(actual.curSection, { path: "N > SG1 > SG2 > S", section: section }, "The curSection property is correct"); }); test("convertNotebookListToState should return the notebook list, success status, and undefined default section in case where there is no default section", () => { let sectionGroup2 = createSectionGroup("SG2", [], []); let sectionGroup1 = createSectionGroup("SG1", [sectionGroup2], []); let notebook = createNotebook("N", true, [sectionGroup1], []); let notebooks = [notebook]; let actual = SectionPickerClass.convertNotebookListToState(notebooks); strictEqual(actual.notebooks, notebooks, "The notebooks property is correct"); strictEqual(actual.status, Status.Succeeded, "The status property is correct"); strictEqual(actual.curSection, undefined, "The curSection property is undefined"); }); test("convertNotebookListToState should return the notebook list, success status, and undefined default section in case where there is only one empty notebook", () => { let notebook = createNotebook("N", true, [], []); let notebooks = [notebook]; let actual = SectionPickerClass.convertNotebookListToState(notebooks); strictEqual(actual.notebooks, notebooks, "The notebooks property is correct"); strictEqual(actual.status, Status.Succeeded, "The status property is correct"); strictEqual(actual.curSection, undefined, "The curSection property is undefined"); }); test("convertNotebookListToState should return the undefined notebook list, success status, and undefined default section if the input is undefined", () => { let actual = SectionPickerClass.convertNotebookListToState(undefined); strictEqual(actual.notebooks, undefined, "The notebooks property is undefined"); strictEqual(actual.status, Status.Succeeded, "The status property is correct"); strictEqual(actual.curSection, undefined, "The curSection property is undefined"); }); test("convertNotebookListToState should return the empty notebook list, success status, and undefined default section if the input is undefined", () => { let actual = SectionPickerClass.convertNotebookListToState([]); strictEqual(actual.notebooks.length, 0, "The notebooks property is the empty list"); strictEqual(actual.status, Status.Succeeded, "The status property is correct"); strictEqual(actual.curSection, undefined, "The curSection property is undefined"); }); test("formatSectionInfoForStorage should return a ' > ' delimited name path and the last element in the general case", () => { let section = createSection("4"); let actual = SectionPickerClass.formatSectionInfoForStorage([ createNotebook("1"), createSectionGroup("2"), createSectionGroup("3"), section ]); deepEqual(actual, { path: "1 > 2 > 3 > 4", section: section }, "The section info should be formatted correctly"); }); test("formatSectionInfoForStorage should return a ' > ' delimited name path and the last element if there are no section groups", () => { let section = createSection("2"); let actual = SectionPickerClass.formatSectionInfoForStorage([ createNotebook("1"), section ]); deepEqual(actual, { path: "1 > 2", section: section }, "The section info should be formatted correctly"); }); test("formatSectionInfoForStorage should return undefined if the list that is passed in is undefined", () => { let actual = SectionPickerClass.formatSectionInfoForStorage(undefined); strictEqual(actual, undefined, "The section info should be formatted correctly"); }); test("formatSectionInfoForStorage should return undefined if the list that is passed in is empty", () => { let actual = SectionPickerClass.formatSectionInfoForStorage([]); strictEqual(actual, undefined, "The section info should be formatted correctly"); }); } } export class SectionPickerSinonTests extends TestModule { private defaultComponent; private mockClipperState = MockProps.getMockClipperState(); private server: sinon.SinonFakeServer; protected module() { return "sectionPicker-sinon"; } protected beforeEach() { this.defaultComponent = <SectionPicker onPopupToggle={() => {}} clipperState={this.mockClipperState} />; this.server = sinon.fakeServer.create(); this.server.respondImmediately = true; } protected afterEach() { this.server.restore(); } protected tests() { test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," + "the user does not make a new selection, and then information is found on the server. Also the notebooks are the same in storage and on the server, " + "and the current section in storage is the same as the default section in the server's notebook list", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "Clipper Test > Full Page", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString); // After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case) let freshNotebooks = MockProps.getMockNotebooks(); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: freshNotebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, JSON.stringify(freshNotebooks), "After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed."); strictEqual(curSection, JSON.stringify(mockSection), "The current selected section in storage should not have changed"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks), "The state should always be updated with the fresh notebooks once it has been retrieved"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection), "Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded"); done(); }); }); }, (error) => { ok(false, "reject should not be called"); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," + "the user does not make a new selection, and then information is found on the server. The notebooks on the server is not the same as the ones in storage, " + "and the current section in storage is the same as the default section in the server's notebook list", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "Clipper Test > Full Page", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // After retrieving fresh notebooks, the storage should be updated with the fresh notebooks let freshNotebooks = MockProps.getMockNotebooks(); freshNotebooks.push(createNotebook("id", false, [], [])); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: freshNotebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, JSON.stringify(freshNotebooks), "After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed."); strictEqual(curSection, JSON.stringify(mockSection), "The current selected section in storage should not have changed"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks), "The state should always be updated with the fresh notebooks once it has been retrieved"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection), "Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded"); done(); }); }); }, (error) => { ok(false, "reject should not be called"); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook, but no curSection information found in storage," + "the user does not make a selection, and then information is found on the server. The notebooks on the server is the same as the ones in storage, " + "and the current section in storage is still undefined by the time the fresh notebooks have been retrieved", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); initializeClipperStorage(JSON.stringify(mockNotebooks), undefined, TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case) let freshNotebooks = MockProps.getMockNotebooks(); freshNotebooks.push(createNotebook("id", false, [], [])); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: freshNotebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); // This is the default section in the mock notebooks, and this should be found in storage and state after fresh notebooks are retrieved let defaultSection = { path: "Clipper Test > Full Page", section: mockNotebooks[0].sections[0] }; controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, JSON.stringify(freshNotebooks), "After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed."); strictEqual(curSection, JSON.stringify(defaultSection), "The current selected section in storage should have been updated with the default section since it was undefined before"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks), "The state should always be updated with the fresh notebooks once it has been retrieved"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(defaultSection), "Since curSection was not found in storage, and the user did not make an action to select another section, it should be updated in state"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded"); done(); }); }); }, (error) => { ok(false, "reject should not be called"); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook, but no curSection information found in storage," + "the user makes a new section selection, and then information is found on the server. The notebooks on the server is the same as the ones in storage, " + "and the current section in storage is still undefined by the time the fresh notebooks have been retrieved", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); initializeClipperStorage(JSON.stringify(mockNotebooks), undefined, TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // The user now clicks on a section (second section of second notebook) MithrilUtils.simulateAction(() => { document.getElementById(TestConstants.Ids.sectionLocationContainer).click(); }); let sectionPicker = document.getElementById(TestConstants.Ids.sectionPickerContainer).firstElementChild; let second = sectionPicker.childNodes[1]; let secondNotebook = second.childNodes[0] as HTMLElement; let secondSections = second.childNodes[1] as HTMLElement; MithrilUtils.simulateAction(() => { secondNotebook.click(); }); let newSelectedSection = secondSections.childNodes[1] as HTMLElement; MithrilUtils.simulateAction(() => { // The clickable element is actually the first childNode (newSelectedSection.childNodes[0] as HTMLElement).click(); }); // This corresponds to the second section of the second notebook in the mock notebooks let selectedSection = { section: mockNotebooks[1].sections[1], path: "Clipper Test 2 > Section Y", parentId: "a-bc!d" }; Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection1) => { strictEqual(curSection1, JSON.stringify(selectedSection), "The current selected section in storage should have been updated with the selected section"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(selectedSection), "The current selected section in state should have been updated with the selected section"); // After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case) let freshNotebooks = MockProps.getMockNotebooks(); freshNotebooks.push(createNotebook("id", false, [], [])); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: freshNotebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection2) => { strictEqual(notebooks, JSON.stringify(freshNotebooks), "After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed."); strictEqual(curSection2, JSON.stringify(selectedSection), "The current selected section in storage should still be the selected section"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks), "The state should always be updated with the fresh notebooks once it has been retrieved"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(selectedSection), "The current selected section in state should still be the selected section"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded"); done(); }); }); }, (error) => { ok(false, "reject should not be called"); }); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," + " and then information is found on the server, but that selected section no longer exists.", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "Clipper Test > Full Page", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (we deleted the cached currently selected section) let freshNotebooks = MockProps.getMockNotebooks(); freshNotebooks[0].sections = []; let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: freshNotebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection2) => { strictEqual(notebooks, JSON.stringify(freshNotebooks), "After fresh notebooks have been retrieved, the storage should be updated with them."); strictEqual(curSection2, undefined, "The current selected section in storage should now be undefined as it no longer exists in the fresh notebooks"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks), "The state should always be updated with the fresh notebooks once it has been retrieved"); strictEqual(controllerInstance.state.curSection, undefined, "The current selected section in state should be undefined"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded"); done(); }); }); }, (error) => { ok(false, "reject should not be called"); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," + "the user does not make a new selection, and then notebooks is incorrectly returned as undefined or null from the server", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "Clipper Test > Full Page", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: undefined }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { ok(false, "resolve should not be called"); }, (error) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, JSON.stringify(mockNotebooks), "After undefined notebooks have been retrieved, the storage should not be updated with them."); strictEqual(curSection, JSON.stringify(mockSection), "The current selected section in storage should not have changed"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(mockNotebooks), "The state should not be updated as retrieving fresh notebooks returned undefined"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection), "Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state"); strictEqual(controllerInstance.state.status, Status.Failed, "The status should be Failed"); done(); }); }); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," + "the user does not make a new selection, and the server returns an error status code", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock let mockNotebooks = MockProps.getMockNotebooks(); let mockSection = { section: mockNotebooks[0].sections[0], path: "Clipper Test > Full Page", parentId: mockNotebooks[0].id }; initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }), "After the component is mounted, the state should be updated to reflect the notebooks and section found in storage"); // After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information let responseJson = {}; this.server.respondWith([404, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { ok(false, "resolve should not be called"); }, (error) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, JSON.stringify(mockNotebooks), "After undefined notebooks have been retrieved, the storage should not be updated with them."); strictEqual(curSection, JSON.stringify(mockSection), "The current selected section in storage should not have changed"); strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(mockNotebooks), "The state should not be updated as retrieving fresh notebooks returned undefined"); strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection), "Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state"); strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded since we have a fallback in storage"); done(); }); }); }); }); test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's no notebook and curSection information found in storage," + "the user does not make a new selection, and the server returns an error status code, therefore there's no fallback notebooks", (assert: QUnitAssert) => { let done = assert.async(); let clipperState = MockProps.getMockClipperState(); // Set up the storage mock initializeClipperStorage(undefined, undefined, TestConstants.defaultUserInfoAsJsonString); let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />; let controllerInstance = MithrilUtils.mountToFixture(component); strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: undefined, status: Status.NotStarted, curSection: undefined }), "After the component is mounted, the state should be updated to reflect that notebooks and current section are not found in storage"); // After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information let responseJson = {}; this.server.respondWith([404, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => { ok(false, "resolve should not be called"); }, (error) => { Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => { Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => { strictEqual(notebooks, undefined, "After undefined notebooks have been retrieved, the storage notebook value should still be undefined"); strictEqual(curSection, undefined, "After undefined notebooks have been retrieved, the storage section value should still be undefined as there was no default section present"); strictEqual(controllerInstance.state.notebooks, undefined, "After undefined notebooks have been retrieved, the state notebook value should still be undefined"); strictEqual(controllerInstance.state.curSection, undefined, "After undefined notebooks have been retrieved, the state section value should still be undefined as there was no default section present"); strictEqual(controllerInstance.state.status, Status.Failed, "The status should be Failed since getting fresh notebooks has failed and we don't have a fallback"); done(); }); }); }); }); test("fetchFreshNotebooks should parse out @odata.context from the raw 200 response and return the notebook object list and XHR in the resolve", (assert: QUnitAssert) => { let done = assert.async(); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let notebooks = MockProps.getMockNotebooks(); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: notebooks }; this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => { strictEqual(JSON.stringify(responsePackage.parsedResponse), JSON.stringify(notebooks), "The notebook list should be present in the response"); ok(!!responsePackage.request, "The XHR must be present in the response"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("fetchFreshNotebooks should parse out @odata.context from the raw 201 response and return the notebook object list and XHR in the resolve", (assert: QUnitAssert) => { let done = assert.async(); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let notebooks = MockProps.getMockNotebooks(); let responseJson = { "@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks", value: notebooks }; this.server.respondWith([201, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]); controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => { strictEqual(JSON.stringify(responsePackage.parsedResponse), JSON.stringify(notebooks), "The notebook list should be present in the response"); ok(!!responsePackage.request, "The XHR must be present in the response"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("fetchFreshNotebooks should reject with the error object and a copy of the response if the status code is 4XX", (assert: QUnitAssert) => { let done = assert.async(); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let responseJson = { error: "Unexpected response status", statusCode: 401, responseHeaders: { "Content-Type": "application/json" } }; let expected = { error: responseJson.error, statusCode: responseJson.statusCode, responseHeaders: responseJson.responseHeaders, response: JSON.stringify(responseJson), timeout: 30000 }; this.server.respondWith([expected.statusCode, expected.responseHeaders, expected.response]); controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, expected, "The error object should be rejected"); strictEqual(controllerInstance.state.apiResponseCode, undefined); }).then(() => { done(); }); }); test("fetchFreshNotebooks should reject with the error object and an API response code if one is returned by the API", (assert: QUnitAssert) => { let done = assert.async(); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let responseJson = { error: { code: "10008", message: "The user's OneDrive, Group or Document Library contains more than 5000 items and cannot be queried using the API.", "@api.url": "http://aka.ms/onenote-errors#C10008" } }; let expected = { error: "Unexpected response status", statusCode: 403, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }; this.server.respondWith([expected.statusCode, expected.responseHeaders, expected.response]); controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => { ok(false, "resolve should not be called"); }, (error: OneNoteApi.RequestError) => { deepEqual(error, expected, "The error object should be rejected"); ok(!OneNoteApiUtils.isRetryable(controllerInstance.state.apiResponseCode)); }).then(() => { done(); }); }); test("fetchFreshNotebooks should reject with the error object and a copy of the response if the status code is 5XX", (assert: QUnitAssert) => { let done = assert.async(); let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent); let responseJson = { error: "Unexpected response status", statusCode: 501, responseHeaders: { "Content-Type": "application/json" } }; this.server.respondWith([501, responseJson.responseHeaders, JSON.stringify(responseJson)]); let expected = { error: responseJson.error, statusCode: responseJson.statusCode, responseHeaders: responseJson.responseHeaders, response: JSON.stringify(responseJson), timeout: 30000 }; controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, expected, "The error object should be rejected"); }).then(() => { done(); }); }); } } (new SectionPickerTests()).runTests(); (new SectionPickerSinonTests()).runTests();
the_stack
import { Translation } from '../i18'; // spanish // // Translated by: Alejandro Iván Melo Domínguez (https://github.com/alejandroivan) export const translation: Translation = { __plugins: { reload: { failed: 'No se pudo recargar plugins: {0}', loaded: { more: '{0:trim} plugins cargados.', none: 'No se cargó plugins.', one: '1 plugin cargado.', } } }, canceled: '[Cancelado]', commands: { executionFailed: "La ejecución del comando {0:trim,surround} falló: {1}", }, compare: { failed: 'No se pudo obtener el archivo {0:trim,surround}: {1}', noPlugins: '¡No se encontró plugin(s)!', noPluginsForType: '¡No se encontró plugin(s) que coincidan con {0:trim,surround}!', selectSource: 'Elige el origen desde donde obtener...', }, deploy: { after: { button: { text: "{2}Desplegar: [{1}] {0}{3}", tooltip: "Haz click aquí para mostrar salida...", // Click here to show output... }, failed: "No se pudo invocar operaciones 'después de desplegar': {0}", }, before: { failed: "No se pudo invocar operaciones 'antes de desplegar': {0}", }, button: { cancelling: 'Cancelando...', prepareText: 'Preparando despliegue...', text: 'Desplegando...', tooltip: 'Haz click aquí para cancelar despliegue...', }, canceled: 'Cancelado.', canceledWithErrors: '¡Cancelado con errores!', cancelling: 'Cancelando despliegue...', file: { deploying: 'Desplegando archivo {0:trim,surround}{1:trim,leading_space}... ', deployingWithDestination: 'Desplegando archivo {0:trim,surround} hacia {1:trim,surround}{2:trim,leading_space}... ', failed: 'No se pudo desplegar archivo {0:trim,surround}: {1}', isIgnored: "¡El archivo {0:trim,surround} ha sido ignorado!", succeeded: 'El archivo {0:trim,surround} se ha desplegado con éxito.', succeededWithTarget: 'El archivo {0:trim,surround} se ha desplegado correctamente hacia {1:trim,surround}.', }, fileOrFolder: { failed: 'No se ha podido desplegar el archivo/carpeta {0:trim,surround}: {1}', }, finished: 'Finalizado.', finished2: 'Finalizado', finishedWithErrors: '¡Finalizado con errores!', folder: { failed: 'No se pudo desplegar la carpeta {0:trim,surround}: {1}', selectTarget: 'Elige el destino donde desplegar la carpeta...', }, newerFiles: { deploy: 'Desplegar', localFile: 'Archivo local', message: "¡Se encontró {0} nuevo(s) archivo(s)!", modifyTime: 'Última modificación', pull: 'Obtener', remoteFile: 'Archivo remoto', show: 'Mostrar archivos', size: 'Tamaño', title: 'Nuevos archivos en {0:trim,surround}', titleNoTarget: 'Nuevos archivos', }, noFiles: '¡No hay archivos para desplegar!', noPlugins: '¡No se encontró plugin(s)!', noPluginsForType: '¡No se encontró plugin(s) que coincidan con {0:trim,surround}!', onSave: { couldNotFindTarget: '¡El destino de despliegue {0:trim,surround} definido en el paquete{1:trim,surround,leading_space} no existe!', failed: 'No se pudo desplegar {0:trim,surround} al guardar ({1:trim}): {2}', failedTarget: 'No se pudo desplegar {0:trim,surround} hacia {1:trim} al guardar: {2}', }, operations: { failed: "[ERROR: {0:trim,surround}]", finished: "[Hecho]", noFileCompiled: "¡Ninguno de los {0:trim} archivos pudo ser compilado!", noFunctionInScript: "¡La función {0:trim,surround} no se encontró en {1:trim,surround}!", open: 'Abriendo {0:trim,surround}... ', someFilesNotCompiled: "¡{0:trim} de {1:trim} archivos no pudieron ser compilados!", unknownCompiler: '¡El compilador {0:trim,surround} es desconocido!', unknownSqlEngine: '¡Motor SQL desconocido! {0:trim,surround}', unknownType: 'TIPO DESCONOCIDO: {0:trim,surround}', }, startQuestion: '¿Iniciar despliegue?', workspace: { allFailed: 'No se pudo desplegar ningún archivo: {0}', allFailedWithTarget: 'No se pudo desplegar ningún archivo hacia {0:trim,surround}: {1}', allSucceeded: 'Los {0:trim} archivos fueron desplegados con éxito.', allSucceededWithTarget: 'Los {0:trim} fueron desplegados con éxito hacia {1:trim,surround}.', alreadyStarted: '¡Ya se inició un despliegue hacia {0:trim,surround}! ¿De verdad quieres iniciar esta operación?', clickToCancel: 'haz click aquí para cancelar', deploying: 'Desplegando paquete{0:trim,surround,leading_space}...', deployingWithTarget: 'Desplegando paquete{0:trim,surround,leading_space} hacia {1:trim,surround}...', failed: 'No se pudo desplegar archivos: {0}', failedWithCategory: 'No se pudo desplegar archivos ({0:trim}): {1}', failedWithTarget: 'No se pudo desplegar archivos hacia {0:trim,surround}: {1}', nothingDeployed: '¡No se desplegó ningún archivo!', nothingDeployedWithTarget: '¡No se pudo desplegar ningún archivo hacia {0:trim,surround}!', selectPackage: 'Elige un paquete...', selectTarget: 'Elige un destino...', someFailed: '¡{0:trim} de {1:trim} archivos no pudieron desplegarse!', someFailedWithTarget: '¡{0:trim} de {1:trim} archivos no pudieron desplegarse hacia {2:trim,surround}!', status: 'Desplegando {0:trim,surround}... ', statusWithDestination: 'Desplegando {0:trim,surround} hacia {1:trim,surround}... ', virtualTargetName: 'Destino virtual por lotes para el paquete actual', // Virtual batch target for current package virtualTargetNameWithPackage: 'Destino virtual por lots para el paquete {0:trim, surround}', // Virtual batch target for package {0:trim,surround} } }, errors: { countable: 'ERROR #{0:trim}: {1}', withCategory: '[ERROR] {0:trim}: {1}', }, extension: { update: "Actualizar...", updateRequired: "¡La extensión requiere una actualización!", }, extensions: { notInstalled: 'La extensión {0:trim,surround} NO se encuentra instalada.', }, failed: '[FALLÓ: {0}]', format: { dateTime: 'HH:mm:ss DD/MM/YYYY', // YYYY-MM-DD HH:mm:ss }, host: { button: { text: 'Esperando archivos...', tooltip: 'Haz click aquí para cerrar el host de despliegue', // Click here to close deploy host }, errors: { cannotListen: 'No se pudo comenzar a escuchar por archivos: {0}', couldNotStop: 'No se pudo detener el host de despliegue: {0}', fileRejected: '¡El archivo ha sido rechazado!', noData: '¡Sin información!', noFilename: '¡Sin archivo {0:trim}!', // No filename {0:trim}! // TODO: NOT SURE ABOUT THIS }, receiveFile: { failed: '[FALLÓ:{0:trim,leading_space}]', ok: '[HECHO{0:trim}]', receiving: "Recibiendo archivo{2:trim,leading_space} desde '{0:trim}:{1:trim}'... ", }, started: 'Iniciado host de despliegue con puerto {0:trim} en el directorio {1:trim,surround}.', stopped: 'El host de despliegue se ha detenido.', }, install: 'Install', isNo: { directory: "¡{0:trim,surround} no es una carpeta!", file: "¡{0:trim,surround} no es un archivo!", validItem: '¡{0:trim,surround} no es un ítem válido para ser desplegado!', }, load: { from: { failed: "La carga de información desde {0:trim,surround} falló: {1}", } }, network: { hostname: 'Tu nombre de host: {0:trim,surround}', interfaces: { failed: 'No se pudo obtener las interfaces de red: {0}', // Could not get network interfaces: {0} list: 'Tus interfaces de red:', // Your network interfaces: } }, ok: '[HECHO]', packages: { couldNotFindTarget: '¡No se pudo encontrar el destino {0:trim,surround} en el paquete {1:trim,surround}!', defaultName: '(Paquete #{0:trim})', noneDefined: "¡Por favor, define al menos un PAQUETE en tu 'settings.json'!", notFound: '¡El paquete {0:trim,surround} no se ha encontrado!', nothingToDeploy: '¡Sin paquetes para desplegar!', }, plugins: { api: { clientErrors: { noPermissions: "¡Sin permisos de escritura!", notFound: '¡Archivo no encontrado!', unauthorized: "¡El usuario no está autorizado!", unknown: "Error de cliente desconocido: {0:trim} {2:trim,surround}", }, description: "Despliega hacia una API REST, como 'vs-rest-api'", serverErrors: { unknown: "Error de servidor desconocido: {0:trim} {2:trim,surround}", }, }, app: { description: 'Despliega hacia una app, como un script o ejecutable, en la máquina local', }, azureblob: { description: 'Despliega hacia blob storage de Microsoft Azure', }, batch: { description: 'Despliega hacia otros destinos', }, dropbox: { description: 'Despliega hacia una carpeta de Dropbox.', notFound: '¡Archivo no encontrado!', unknownResponse: 'Respuesta inesperada {0:trim} ({1:trim}): {2:trim,surround}', }, each: { description: 'Despliega archivos usando una lista de valores', // Deploys files by using a list of values }, ftp: { description: 'Despliega hacia un servidor FTP', }, http: { description: 'Despliega hacia un servidor/servicio HTTP', protocolNotSupported: '¡El protocolo {0:trim,surround} no está soportado!', }, list: { description: 'Deja al usuario elegir una entrada con ajustes para uno o más destinos', // Lets the user select an entry with settings for one or more targets selectEntry: 'Por favor, elige una entrada...', }, local: { description: 'Despliega hacia una carpeta local o compartida (como SMB) dentro de tu red de área local (LAN)', emptyTargetDirectory: 'Directorio de destino LOCAL vacío {0:trim, surround}... ', // Empty LOCAL target directory {0:trim,surround}... }, mail: { addressSelector: { placeholder: 'Dirección(es) de correo electrónico de destino', // Target eMail address(es) prompt: 'Una o más direcciones de correo electrónico (separadas por comas) hacia donde desplegar...', // One or more email address (separated by comma) to deploy to... }, description: 'Despliega hacia un archivo ZIP y lo envía como archivo adjunto de correo electrónico mediante SMTP', // Deploys to a ZIP file and sends it as attachment by mail via SMTP }, map: { description: 'Despliega archivos utilizando una lista de valores', // Deploys files by using a list of values }, pipeline: { description: 'Utilizando un script, efectúa un pipe de una lista de archivos fuente hacia un nuevo objetivo y envía la nueva lista de archivos a un destino', // Pipes a list of sources files to a new destination, by using a script and sends the new file list to a target noPipeFunction: "¡{0:trim,surround} no implementa una función 'pipe()'!", }, prompt: { description: "Pregunta al usuario por una lista de ajustes que será aplicada a uno o más destinos", // Asks the user for a list of settings that will be applied to one or more targets invalidInput: "¡Entrada inválida!", }, remote: { description: 'Despliega hacia una máquina remota usando una conexión TCP', // Deploys to a remote machine over a TCP connection }, s3bucket: { credentialTypeNotSupported: '¡El tipo de credencial {0:trim,surround} no está soportada!', description: 'Despliega hacia un bucket de Amazon S3', }, script: { deployFileFailed: '¡No se pudo desplegar el archivo {0:trim,surround} utilizando el script {1:trim,surround}!', deployWorkspaceFailed: '¡No se pudo desplegar el espacio de trabajo utilizando el script {0:trim,surround}!', description: 'Despliega mediante un script JS', noDeployFileFunction: "¡{0:trim,surround} no implementa una función 'deployFile()'!", }, sftp: { description: 'Despliega hacia un servidor SFTP', }, sql: { description: 'Ejecuta scripts SQL', invalidFile: '¡El archivo es inválido!', unknownEngine: '¡El motor {0:trim,surround} es desconocido!', }, test: { description: 'Un despliegue fingido que solo muestra qué archivos serían desplegados', // A mock deployer that only displays what files would be deployed }, zip: { description: 'Despliega hacia un archivo ZIP', fileAlreadyExists: '¡El archivo {0:trim,surround} ya existe! Intenta nuevamente...', fileNotFound: '¡El archivo no se ha encontrado!', noFileFound: "¡No se encontró archivos ZIP!", } }, popups: { newVersion: { message: "¡Estás ejecutando la nueva versión de 'vs-deploy' ({0:trim})!", showChangeLog: 'Mostrar registro de cambios...', }, }, prompts: { inputAccessKey: 'Ingresa la clave de acceso...', inputAccessToken: 'Ingresa el token de acceso...', inputPassword: 'Ingresa la contraseña...', }, pull: { button: { cancelling: 'Cancelando...', prepareText: 'Preparando obtención...', text: 'Obteniendo...', tooltip: 'Haz click aquí para cancelar la obtención...', }, canceled: 'Cancelado.', canceledWithErrors: '¡Cancelado con errores!', file: { failed: 'No se pudo obtener el archivo {0:trim,surround}: {1}', pulling: 'Obteniendo el archivo {0:trim,surround}{1:trim,leading_space}... ', pullingWithDestination: 'Obteniendo el archivo {0:trim,surround} desde {1:trim,surround}{2:trim,leading_space}... ', succeeded: 'El archivo {0:trim,surround} se ha obtenido con éxito.', succeededWithTarget: 'El archivo {0:trim,surround} se ha obtenido con éxito desde {1:trim,surround}.', }, fileOrFolder: { failed: "No se pudo obtener el archivo/directorio {0:trim,surround}: {1}", }, finished2: 'Finalizado', finishedWithErrors: '¡Finalizado con errores!', noPlugins: '¡No se encontró plugin(s)!', noPluginsForType: '¡No se encontró plugin(s) que coincidan con {0:trim,surround}!', workspace: { allFailed: 'No se pudo obtener ningún archivo: {0}', allFailedWithTarget: 'No se pudo obtener ningún archivo desde {0:trim,surround}: {1}', allSucceeded: 'Los {0:trim} archivos fueron obtenidos con éxito.', allSucceededWithTarget: 'Los {0:trim} archivos fueron obtenidos con éxito desde {1:trim,surround}.', alreadyStarted: '¡Ya has iniciado una operación para {0:trim,surround}! ¿De verdad quieres iniciar esta operación?', clickToCancel: 'haz click aquí para cancelar', failed: 'No se pudo obtener archivos: {0}', failedWithCategory: 'No se pudo obtener archivos ({0:trim}): {1}', failedWithTarget: 'No se pudo obtener archivos desde {0:trim,surround}: {1}', nothingPulled: '¡No se ha obtenido ningún archivo!', nothingPulledWithTarget: '¡No se ha obtenido ningún archivo desde {0:trim,surround}!', pulling: 'Obteniendo paquete{0:trim,surround,leading_space}...', pullingWithTarget: 'Obteniendo paquete{0:trim,surround,leading_space} desde {1:trim,surround}...', selectPackage: 'Elige un paquete...', selectSource: 'Elige un origen...', someFailed: '¡No se pudo obtener {0:trim} de {1:trim} archivo(s)!', someFailedWithTarget: '¡No se pudo obtener {0:trim} de {1:trim} archivo(s) desde {2:trim,surround}!', status: 'Obteniendo {0:trim,surround}... ', statusWithDestination: 'Obteniendo {0:trim,surround} desde {1:trim,surround}... ', virtualTargetName: 'Destino virtual por lotes para el paquete actual', virtualTargetNameWithPackage: 'Destino virtual por lotes para el paquete {0:trim,surround}', } }, quickDeploy: { caption: '¡Despliegue rápido!', failed: 'El despliegue rápido falló: {0}', start: 'Iniciar un despliegue rápido...', }, relativePaths: { couldNotResolve: "¡No se pudo obtener la ruta relativa para {0:trim,surround}!", isEmpty: '¡La ruta relativa para {0:trim,surround} está vacía!', }, sync: { file: { doesNotExistOnRemote: '[no existe en el remoto]', // [remote does not exist] // TRANSLATION: 'does not exist on remote' // TODO: Check localChangedWithinSession: '[el local cambió durante la sesión]', localIsNewer: '[el local es más nuevo]', synchronize: 'Sincronizar archivo {0:trim,surround}{1:trim,leading_space}... ', } }, targets: { cannotUseRecurrence: '¡No se puede usar el destino {0:trim,surround} (recurrencia)!', defaultName: '(Destino #{0:trim})', noneDefined: "¡Por favor, define al menos un DESTINO en tu 'settings.json'!", notFound: '¡No se pudo encontrar el destino {0:trim,surround}!', select: 'Elige el destino hacia donde desplegar...', selectSource: 'Elige el origen desde donde obtener...', }, templates: { browserTitle: "Tema{0:trim,surround,leading_space}", currentPath: 'Ruta actual:{0:trim,leading_space}', noneDefined: "¡Por favor, define al menos un ORIGEN DE TEMA en tu 'settings.json'!", // Please define a least one TEMPLATE SOURCE in your 'settings.json'! officialRepositories: { newAvailable: "Los ORÍGENES DE TEMA oficiales se han actualizado.", openTemplates: "Abrir temas...", }, placeholder: 'Por favor, elige un ítem...', publishOrRequest: { label: 'Publicar o solicitar un ejemplo...', } }, warnings: { withCategory: '[ADVERTENCIA] {0:trim}: {1}', }, yes: 'Sí', };
the_stack
import { build as buildQueryParams, IOptions, parse as parseQueryParams } from 'search-params' import { URLParamsEncodingType, decodeParam, encodeParam } from './encoding' import { defaultOrConstrained } from './rules' import tokenise, { Token } from './tokeniser' export { URLParamsEncodingType } const exists = (val: any) => val !== undefined && val !== null const optTrailingSlash = (source: string, strictTrailingSlash: boolean) => { if (strictTrailingSlash) { return source } if (source === '\\/') { return source } return source.replace(/\\\/$/, '') + '(?:\\/)?' } const upToDelimiter = (source: string, delimiter?: boolean) => { if (!delimiter) { return source } return /(\/)$/.test(source) ? source : source + '(\\/|\\?|\\.|;|$)' } const appendQueryParam = ( params: Record<string, any>, param: string, val = '' ) => { const existingVal = params[param] if (existingVal === undefined) { params[param] = val } else { params[param] = Array.isArray(existingVal) ? existingVal.concat(val) : [existingVal, val] } return params } export interface PathOptions { /** * Query parameters buiding and matching options, see * https://github.com/troch/search-params#options */ queryParams?: IOptions /** * Specifies the method used to encode URL parameters: * - `'default': `encodeURIComponent` and `decodeURIComponent` * are used but some characters to encode and decode URL parameters, * but some characters are preserved when encoding * (sub-delimiters: `+`, `:`, `'`, `!`, `,`, `;`, `'*'`). * - `'uriComponent'`: use `encodeURIComponent` and `decodeURIComponent` * for encoding and decoding URL parameters. * - `'uri'`: use `encodeURI` and `decodeURI for encoding amd decoding * URL parameters. * - `'none'`: no encoding or decoding is performed * - `'legacy'`: the approach for version 5.x and below (not recoomended) */ urlParamsEncoding?: URLParamsEncodingType } export interface InternalPathOptions { queryParams?: IOptions urlParamsEncoding: URLParamsEncodingType } const defaultOptions: InternalPathOptions = { urlParamsEncoding: 'default' } export interface PathPartialTestOptions extends PathOptions { caseSensitive?: boolean delimited?: boolean } export interface PathTestOptions extends PathOptions { caseSensitive?: boolean strictTrailingSlash?: boolean } export interface PathBuildOptions extends PathOptions { ignoreConstraints?: boolean ignoreSearch?: boolean } export type TestMatch< T extends Record<string, any> = Record<string, any> > = T | null export class Path<T extends Record<string, any> = Record<string, any>> { public static createPath<T extends Record<string, any> = Record<string, any>>( path: string, options?: PathOptions ) { return new Path<T>(path, options) } public path: string public tokens: Token[] public hasUrlParams: boolean public hasSpatParam: boolean public hasMatrixParams: boolean public hasQueryParams: boolean public options: InternalPathOptions public spatParams: string[] public urlParams: string[] public queryParams: string[] public params: string[] public source: string constructor(path: string, options?: PathOptions) { if (!path) { throw new Error('Missing path in Path constructor') } this.path = path this.options = { ...defaultOptions, ...options } this.tokens = tokenise(path) this.hasUrlParams = this.tokens.filter(t => /^url-parameter/.test(t.type)).length > 0 this.hasSpatParam = this.tokens.filter(t => /splat$/.test(t.type)).length > 0 this.hasMatrixParams = this.tokens.filter(t => /matrix$/.test(t.type)).length > 0 this.hasQueryParams = this.tokens.filter(t => /^query-parameter/.test(t.type)).length > 0 // Extract named parameters from tokens this.spatParams = this.getParams('url-parameter-splat') this.urlParams = this.getParams(/^url-parameter/) // Query params this.queryParams = this.getParams('query-parameter') // All params this.params = this.urlParams.concat(this.queryParams) // Check if hasQueryParams // Regular expressions for url part only (full and partial match) this.source = this.tokens .filter(t => t.regex !== undefined) .map(t => t.regex!.source) .join('') } public isQueryParam(name: string): boolean { return this.queryParams.indexOf(name) !== -1 } public isSpatParam(name: string): boolean { return this.spatParams.indexOf(name) !== -1 } public test(path: string, opts?: PathTestOptions): TestMatch<T> { const options = { caseSensitive: false, strictTrailingSlash: false, ...this.options, ...opts } as const // trailingSlash: falsy => non optional, truthy => optional const source = optTrailingSlash(this.source, options.strictTrailingSlash) // Check if exact match const match = this.urlTest( path, source + (this.hasQueryParams ? '(\\?.*$|$)' : '$'), options.caseSensitive, options.urlParamsEncoding ) // If no match, or no query params, no need to go further if (!match || !this.hasQueryParams) { return match } // Extract query params const queryParams = parseQueryParams(path, options.queryParams) const unexpectedQueryParams = Object.keys(queryParams).filter( p => !this.isQueryParam(p) ) if (unexpectedQueryParams.length === 0) { // Extend url match Object.keys(queryParams).forEach( // @ts-ignore p => (match[p] = (queryParams as any)[p]) ) return match } return null } public partialTest( path: string, opts?: PathPartialTestOptions ): TestMatch<T> { const options = { caseSensitive: false, delimited: true, ...this.options, ...opts } as const // Check if partial match (start of given path matches regex) // trailingSlash: falsy => non optional, truthy => optional const source = upToDelimiter(this.source, options.delimited) const match = this.urlTest( path, source, options.caseSensitive, options.urlParamsEncoding ) if (!match) { return match } if (!this.hasQueryParams) { return match } const queryParams = parseQueryParams(path, options.queryParams) Object.keys(queryParams) .filter(p => this.isQueryParam(p)) .forEach(p => appendQueryParam(match, p, (queryParams as any)[p])) return match } public build(params: T = {} as T, opts?: PathBuildOptions): string { const options = { ignoreConstraints: false, ignoreSearch: false, queryParams: {}, ...this.options, ...opts } as const const encodedUrlParams = Object.keys(params) .filter(p => !this.isQueryParam(p)) .reduce<Record<string, any>>((acc, key) => { if (!exists(params[key])) { return acc } const val = params[key] const isSpatParam = this.isSpatParam(key) if (typeof val === 'boolean') { acc[key] = val } else if (Array.isArray(val)) { acc[key] = val.map(v => encodeParam(v, options.urlParamsEncoding, isSpatParam) ) } else { acc[key] = encodeParam(val, options.urlParamsEncoding, isSpatParam) } return acc }, {}) // Check all params are provided (not search parameters which are optional) if (this.urlParams.some(p => !exists(params[p]))) { const missingParameters = this.urlParams.filter(p => !exists(params[p])) throw new Error( "Cannot build path: '" + this.path + "' requires missing parameters { " + missingParameters.join(', ') + ' }' ) } // Check constraints if (!options.ignoreConstraints) { const constraintsPassed = this.tokens .filter(t => /^url-parameter/.test(t.type) && !/-splat$/.test(t.type)) .every(t => new RegExp('^' + defaultOrConstrained(t.otherVal[0]) + '$').test( encodedUrlParams[t.val] ) ) if (!constraintsPassed) { throw new Error( `Some parameters of '${this.path}' are of invalid format` ) } } const base = this.tokens .filter(t => /^query-parameter/.test(t.type) === false) .map(t => { if (t.type === 'url-parameter-matrix') { return `;${t.val}=${encodedUrlParams[t.val[0]]}` } return /^url-parameter/.test(t.type) ? encodedUrlParams[t.val[0]] : t.match }) .join('') if (options.ignoreSearch) { return base } const searchParams = this.queryParams .filter(p => Object.keys(params).indexOf(p) !== -1) .reduce<Record<string, any>>((sparams, paramName) => { sparams[paramName] = params[paramName] return sparams }, {}) const searchPart = buildQueryParams(searchParams, options.queryParams) return searchPart ? base + '?' + searchPart : base } private getParams(type: string | RegExp): string[] { const predicate = type instanceof RegExp ? (t: Token) => type.test(t.type) : (t: Token) => t.type === type return this.tokens.filter(predicate).map(t => t.val[0]) } private urlTest( path: string, source: string, caseSensitive: boolean, urlParamsEncoding: URLParamsEncodingType ): TestMatch<T> { const regex = new RegExp('^' + source, caseSensitive ? '' : 'i') const match = path.match(regex) if (!match) { return null } else if (!this.urlParams.length) { return {} as T } // Reduce named params to key-value pairs return match .slice(1, this.urlParams.length + 1) .reduce<Record<string, any>>((params, m, i) => { params[this.urlParams[i]] = decodeParam(m, urlParamsEncoding) return params }, {}) as T } } export default Path
the_stack
import * as mockery from 'mockery'; import * as assert from 'assert'; import * as sinon from 'sinon'; import {utils, ChromeDebugAdapter, ChromeConnection, chromeTargetDiscoveryStrategy, logger} from 'vscode-chrome-debug-core'; /** Not mocked - use for type only */ import {IOSDebugAdapter as _IOSDebugAdapter} from '../src/iosDebugAdapter'; const MODULE_UNDER_TEST = '../src/iosDebugAdapter'; suite('IOSDebugAdapter', () => { function createAdapter(): _IOSDebugAdapter { const IOSDebugAdapter: typeof _IOSDebugAdapter = require(MODULE_UNDER_TEST).IOSDebugAdapter; const targetFilter = target => target && (!target.type || target.type === 'page'); const connection = new ChromeConnection(chromeTargetDiscoveryStrategy.getChromeTargetWebSocketURL, targetFilter); return new IOSDebugAdapter(connection); }; setup(() => { mockery.enable({ useCleanCache: true, warnOnReplace: false }); mockery.registerAllowables([MODULE_UNDER_TEST, './utilities', 'path', 'child_process']); mockery.warnOnUnregistered(false); // The npm packages pull in too many modules to list all as allowable // Stub wrapMethod to create a function if it doesn's already exist let originalWrap = (<any>sinon).wrapMethod; sinon.stub(sinon, 'wrapMethod', function(...args) { if (!args[0][args[1]]) { args[0][args[1]] = () => { }; } return originalWrap.apply(this, args); }); }); teardown(() => { (<any>sinon).wrapMethod.restore(); mockery.deregisterAll(); mockery.disable(); }); suite('launch()', () => { suite('no port', () => { test('if no port, rejects the launch promise', done => { mockery.registerMock('vscode-chrome-debug-core', { ChromeDebugAdapter: () => { }, utils: utils, logger: logger }); const adapter = createAdapter(); return adapter.launch({}).then( () => assert.fail('Expecting promise to be rejected'), e => done() ); }); }); suite('start server', () => { let adapterMock; let chromeConnectionMock; let utilitiesMock; let cpMock; let MockUtilities; let MockChromeConnection; setup(() => { let deviceInfo = [ { url: 'localhost:' + 8080, deviceName: 'iphone1' }, { url: 'localhost:' + (8080 + 1), deviceName: 'iphone2' } ]; MockChromeConnection = { }; class MockAdapter { public _chromeConnection = MockChromeConnection; }; class MockChildProcess { }; MockUtilities = { Platform: { Windows: 0, OSX: 1, Linux: 2 } }; mockery.registerMock('vscode-chrome-debug-core', { ChromeDebugAdapter: MockAdapter, utils: MockUtilities, logger: logger }); mockery.registerMock('child_process', MockChildProcess); adapterMock = sinon.mock(MockAdapter.prototype); adapterMock.expects('setupLogging').once(); adapterMock.expects('attach').returns(Promise.resolve('')); chromeConnectionMock = sinon.mock(MockChromeConnection); chromeConnectionMock.expects('sendMessage').withArgs("Page.navigate"); utilitiesMock = sinon.mock(MockUtilities); utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); sinon.stub(MockUtilities, 'errP', () => Promise.reject('')); cpMock = sinon.mock(MockChildProcess); cpMock.expects('spawn').once().returns({ unref: () => { }, on: () => { } }); }); teardown(() => { chromeConnectionMock.verify(); adapterMock.verify(); utilitiesMock.verify(); cpMock.verify(); }); test('no settings should skip tunnel', done => { let isTunnelCreated = false; var MockServer = {}; var MockTunnel = () => { isTunnelCreated = true; }; mockery.registerMock('localtunnel', MockTunnel); const adapter = createAdapter(); return adapter.launch({ port: 1234, proxyExecutable: 'test.exe' }).then( () => { assert.equal(isTunnelCreated, false, "Should not create tunnel"); return done(); }, e => assert.fail('Expecting promise to succeed') ); }); suite('with settings', () => { let isTunnelCreated: boolean; let expectedWebRoot: string; let expectedPort: number; let instanceMock; let MockServer = {}; let MockTunnelInstance = {}; setup(() => { isTunnelCreated = false; expectedWebRoot = "root"; expectedPort = 8080; var MockTunnel = (a, f) => { isTunnelCreated = true; f(null, MockTunnelInstance); }; MockTunnelInstance = { url: "index.html" }; mockery.registerMock('localtunnel', MockTunnel); instanceMock = sinon.mock(MockTunnelInstance); instanceMock.expects("on").once(); }); teardown(() => { assert.equal(isTunnelCreated, true, "Should create tunnel"); instanceMock.verify(); }); test('tunnelPort alone should start the localtunnel', done => { const adapter = createAdapter(); return adapter.launch({ port: 1234, proxyExecutable: 'test.exe', tunnelPort: 9283 }).then( () => done(), e => assert.fail('Expecting promise to succeed') ); }); test('tunnelPort should use tunnel url', done => { let expectedUrl = "http://localtunnel.me/path/"; MockTunnelInstance = { url: expectedUrl }; instanceMock = sinon.mock(MockTunnelInstance); instanceMock.expects("on").once(); chromeConnectionMock.restore(); chromeConnectionMock = sinon.mock(MockChromeConnection); chromeConnectionMock.expects('sendMessage').withArgs("Page.navigate", {url: expectedUrl}); const adapter = createAdapter(); return adapter.launch({ port: 1234, proxyExecutable: 'test.exe', tunnelPort: 9283 }).then( () => done(), e => assert.fail('Expecting promise to succeed') ); }); test('tunnelPort should merge url', done => { let tunnelUrl = "http://localtunnel.me/"; let argsUrl = "http://website.com/index.html"; let expectedUrl = tunnelUrl + "index.html"; MockTunnelInstance = { url: tunnelUrl }; instanceMock = sinon.mock(MockTunnelInstance); instanceMock.expects("on").once(); chromeConnectionMock.restore(); chromeConnectionMock = sinon.mock(MockChromeConnection); chromeConnectionMock.expects('sendMessage').withArgs("Page.navigate", {url: expectedUrl}); const adapter = createAdapter(); return adapter.launch({ port: 1234, proxyExecutable: 'test.exe', tunnelPort: 9283, url: argsUrl }).then( () => done(), e => assert.fail('Expecting promise to succeed') ); }); }); }); }); suite('attach()', () => { suite('no port', () => { test('if no port, rejects the attach promise', done => { mockery.registerMock('vscode-chrome-debug-core', { ChromeDebugAdapter: () => { }, utils: utils, logger: logger }); const adapter = createAdapter(); return adapter.attach({}).then( () => assert.fail('Expecting promise to be rejected'), e => done() ); }); }); suite('valid port', () => { let adapterMock; let utilitiesMock; let cpMock; let MockUtilities; setup(() => { class MockAdapter { }; class MockChildProcess { }; MockUtilities = { Platform: { Windows: 0, OSX: 1, Linux: 2 } }; mockery.registerMock('vscode-chrome-debug-core', { ChromeDebugAdapter: MockAdapter, utils: MockUtilities, logger: logger }); mockery.registerMock('child_process', MockChildProcess); adapterMock = sinon.mock(MockAdapter.prototype); adapterMock.expects('setupLogging').once(); utilitiesMock = sinon.mock(MockUtilities); sinon.stub(MockUtilities, 'errP', () => Promise.reject('')); cpMock = sinon.mock(MockChildProcess); }); teardown(() => { adapterMock.verify(); utilitiesMock.verify(); cpMock.verify(); }); test('if no proxy, returns error on osx', done => { sinon.stub(MockUtilities, 'getPlatform', () => MockUtilities.Platform.OSX); const adapter = createAdapter(); return adapter.attach({ port: 1234 }).then( () => assert.fail('Expecting promise to be rejected'), e => { adapterMock.verify(); return done(); } ); }); test('if no proxy, returns error on linux', done => { sinon.stub(MockUtilities, 'getPlatform', () => MockUtilities.Platform.Linux); const adapter = createAdapter(); return adapter.attach({ port: 1234 }).then( () => assert.fail('Expecting promise to be rejected'), e => { adapterMock.verify(); return done(); } ); }); test('if no proxy, returns error on windows', done => { sinon.stub(MockUtilities, 'getPlatform', () => MockUtilities.Platform.Windows); sinon.stub(MockUtilities, 'existsSync', () => false); const adapter = createAdapter(); return adapter.attach({ port: 1234 }).then( () => assert.fail('Expecting promise to be rejected'), e => { adapterMock.verify(); return done(); } ); }); test('if valid port and proxy path, spawns the proxy', done => { sinon.stub(MockUtilities, 'getPlatform', () => MockUtilities.Platform.Windows); sinon.stub(MockUtilities, 'existsSync', () => true); utilitiesMock.expects('getURL').returns(Promise.reject('')); cpMock.expects('spawn').once().returns({ unref: () => { }, on: () => { } }); const adapter = createAdapter(); return adapter.attach({ port: 1234 }).then( () => assert.fail('Expecting promise to be rejected'), e => { adapterMock.verify(); utilitiesMock.verify(); cpMock.verify(); return done(); } ); }); }); suite('device', () => { let adapterMock; let utilitiesMock; let cpMock; setup(() => { class MockAdapter { }; class MockChildProcess { }; var MockUtilities = { Platform: { Windows: 0, OSX: 1, Linux: 2 }, Logger: { log: () => { } } }; mockery.registerMock('vscode-chrome-debug-core', { ChromeDebugAdapter: MockAdapter, utils: MockUtilities, logger: logger }); mockery.registerMock('child_process', MockChildProcess); adapterMock = sinon.mock(MockAdapter.prototype); adapterMock.expects('setupLogging').once(); utilitiesMock = sinon.mock(MockUtilities); cpMock = sinon.mock(MockChildProcess); cpMock.expects('spawn').once().returns({ unref: () => { }, on: () => { } }); }); teardown(() => { adapterMock.verify(); utilitiesMock.verify(); cpMock.verify(); }); test('if no proxy data, returns the proxy port', done => { let proxyPort = 1234; let deviceInfo = []; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: proxyPort, cwd: '' })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe' }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); test('if valid proxy data, returns the first device port', done => { let proxyPort = 1234; let devicePort = 9999; let deviceInfo = [ { url: 'localhost:' + devicePort, deviceName: 'iphone1' }, { url: 'localhost:' + (devicePort + 1), deviceName: 'iphone2' } ]; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: devicePort, cwd: '' })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe' }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); test('if valid proxy data and unknown deviceName, returns the first device port', done => { let proxyPort = 1234; let devicePort = 9999; let deviceInfo = [ { url: 'localhost:' + devicePort, deviceName: 'iphone1' }, { url: 'localhost:' + (devicePort + 1), deviceName: 'iphone2' } ]; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: devicePort, cwd: '' })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe', deviceName: 'nophone' }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); test('if valid proxy data and * deviceName, returns the first device port', done => { let proxyPort = 1234; let devicePort = 9999; let deviceInfo = [ { url: 'localhost:' + devicePort, deviceName: 'iphone1' }, { url: 'localhost:' + (devicePort + 1), deviceName: 'iphone2' } ]; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: devicePort, cwd: '' })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe', deviceName: '*' }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); test('if valid proxy data and valid deviceName, returns the matching device port', done => { let proxyPort = 1234; let devicePort = 9999; let deviceInfo = [ { url: 'localhost:' + devicePort, deviceName: 'iphone1' }, { url: 'localhost:' + (devicePort + 1), deviceName: 'iphone2' } ]; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: devicePort + 1, cwd: '' })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe', deviceName: 'IPHonE2' }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); test('passes on sourceMaps argument', done => { let proxyPort = 1234; let deviceInfo = []; utilitiesMock.expects('getURL').returns(Promise.resolve(JSON.stringify(deviceInfo))); adapterMock.expects('attach').withArgs(sinon.match({ port: proxyPort, cwd: '', sourceMaps: true })).returns(Promise.resolve('')); const adapter = createAdapter(); return adapter.attach({ port: proxyPort, proxyExecutable: 'test.exe', sourceMaps: true }).then( done(), e => assert.fail('Expecting promise to succeed') ); }); }); }); });
the_stack
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { IdentityService } from '../services/identity.service'; import { ClientService } from '../services/client.service'; import { InitializationService } from '../services/initialization.service'; import { AlertService } from '../basic-modals/alert.service'; import { DeleteComponent } from '../basic-modals/delete-confirm/delete-confirm.component'; import { ConnectConfirmComponent } from '../basic-modals/connect-confirm/connect-confirm.component'; import { IdentityCardService } from '../services/identity-card.service'; import { ConfigService } from '../services/config.service'; import { Config } from '../services/config/configStructure.service'; import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { DrawerDismissReasons, DrawerService } from '../common/drawer'; import { ImportIdentityComponent } from './import-identity'; import { IdCard } from 'composer-common'; import { saveAs } from 'file-saver'; import { SampleBusinessNetworkService } from '../services/samplebusinessnetwork.service'; import { AdminService } from '../services/admin.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: [ './login.component.scss'.toString() ] }) export class LoginComponent implements OnInit { private usingLocally: boolean = false; private connectionProfileRefs: string[]; private connectionProfileNames: Map<string, string>; private connectionProfiles: Map<string, string>; private idCardRefs: Map<string, string[]>; private idCards: Map<string, IdCard>; private indestructibleCards: string[]; private showDeployNetwork: boolean = false; private editingConnectionProfile = null; private creatingIdCard: boolean = false; private showSubScreen: boolean = false; private showCredentials: boolean = true; private config = new Config(); constructor(private router: Router, private route: ActivatedRoute, private clientService: ClientService, private initializationService: InitializationService, private identityCardService: IdentityCardService, private modalService: NgbModal, private drawerService: DrawerService, private alertService: AlertService, private configService: ConfigService, private sampleBusinessNetworkService: SampleBusinessNetworkService, private adminService: AdminService) { } ngOnInit(): Promise<void> { return this.initializationService.initialize() .then(() => { this.usingLocally = !this.configService.isWebOnly(); this.config = this.configService.getConfig(); return this.loadIdentityCards(); }).then(() => { this.router.events.subscribe((event) => { console.log('ROUTER SUB', event); if (event instanceof NavigationEnd) { this.handleRouteChange(); } }); this.handleRouteChange(); }); } handleRouteChange() { switch (this.route.snapshot.fragment) { case 'deploy': this.deployNetwork(decodeURIComponent(this.route.snapshot.queryParams['ref'])); break; case 'create-card': this.createIdCard(); break; default: if (this.route.snapshot.fragment || Object.keys(this.route.snapshot.queryParams).length > 0) { this.goLoginMain(); } else { this.closeSubView(); } break; } } goLoginMain(): void { this.router.navigate(['/login']); } goDeploy(connectionProfileRef): void { this.router.navigate(['/login'], {fragment: 'deploy', queryParams: {ref: connectionProfileRef}}); } goCreateCard(): void { this.router.navigate(['/login'], {fragment: 'create-card'}); } loadIdentityCards(reload: boolean = false): Promise<void> { return this.identityCardService.getIdentityCards(reload).then((cards) => { this.indestructibleCards = this.identityCardService.getIndestructibleIdentityCards(); this.idCards = cards; this.connectionProfileNames = new Map<string, string>(); this.connectionProfiles = new Map<string, string>(); let newCardRefs = Array.from(cards.keys()) .map((cardRef) => { let card = cards.get(cardRef); let connectionProfile = card.getConnectionProfile(); if (connectionProfile['x-type'] === 'web' && (this.indestructibleCards.indexOf(cardRef) > -1)) { return; } let connectionProfileRef: string = this.identityCardService.getQualifiedProfileName(connectionProfile); if (!this.connectionProfileNames.has(connectionProfileRef)) { this.connectionProfileNames.set(connectionProfileRef, connectionProfile.name); this.connectionProfiles.set(connectionProfileRef, connectionProfile); } return [connectionProfileRef, cardRef]; }) .reduce((prev, cur) => { if (!cur) { return prev; } let curCardRefs: string[] = prev.get(cur[0]) || []; let cardRef: string = <string> cur[1]; return prev.set(cur[0], [...curCardRefs, cardRef]); }, new Map<string, string[]>()); newCardRefs.forEach((cardRefs: string[], key: string) => { cardRefs.sort(this.sortIdCards.bind(this)); }); // sort connection profile names and make sure there is always // a web connection profile at the start, even when there are // no identity cards let unsortedConnectionProfiles = Array.from(this.connectionProfileNames.keys()); let indexOfWebProfile = unsortedConnectionProfiles.indexOf('web-$default'); if (indexOfWebProfile > -1) { unsortedConnectionProfiles.splice(indexOfWebProfile, 1); } unsortedConnectionProfiles.sort((a: string, b: string): number => { let aName = this.connectionProfileNames.get(a); let bName = this.connectionProfileNames.get(b); if (aName < bName) { return -1; } if (aName > bName) { return 1; } }); unsortedConnectionProfiles.push('web-$default'); this.connectionProfileRefs = unsortedConnectionProfiles; this.idCardRefs = newCardRefs; }).catch((error) => { this.alertService.errorStatus$.next(error); }); } changeIdentity(cardRef: string, connectionProfileRef: string): Promise<boolean | void> { let card = this.idCards.get(cardRef); let businessNetworkName = card.getBusinessNetworkName(); let confirmConnectPromise: Promise<void>; if (this.canDeploy(connectionProfileRef)) { confirmConnectPromise = Promise.resolve(); } else { // Show a warning if the business network cannot be updated const confirmModalRef = this.modalService.open(ConnectConfirmComponent); confirmModalRef.componentInstance.network = businessNetworkName; confirmConnectPromise = confirmModalRef.result; } return confirmConnectPromise .then((result) => { return this.identityCardService.setCurrentIdentityCard(cardRef); }) .then(() => { return this.clientService.ensureConnected(true); }) .then(() => { return this.router.navigate(['editor']); }) .catch((error) => { if (error && error !== ModalDismissReasons.BACKDROP_CLICK && error !== ModalDismissReasons.ESC) { this.alertService.errorStatus$.next(error); } }); } deploySample(connectionProfileRef): Promise<boolean | void> { let peerCardRef = this.identityCardService.getIdentityCardRefsWithProfileAndRole(connectionProfileRef, 'PeerAdmin')[0]; this.identityCardService.setCurrentIdentityCard(peerCardRef); this.alertService.busyStatus$.next({ title: 'Getting sample network', force: true }); return this.sampleBusinessNetworkService.getSampleList() .then((sampleList) => { let chosenSample = sampleList[0]; return this.sampleBusinessNetworkService.getChosenSample(chosenSample); }) .then((businessNetworkDefinition) => { return this.sampleBusinessNetworkService.deployBusinessNetwork(businessNetworkDefinition, 'playgroundSample@basic-sample-network', 'my-basic-sample', 'The Composer basic sample network', null, null, null); }) .then(() => { return this.loadIdentityCards(true); }) .then(() => { this.alertService.busyStatus$.next({ title: 'Connecting to network', force: true }); return this.changeIdentity('playgroundSample@basic-sample-network', connectionProfileRef); }); } editConnectionProfile(connectionProfile): void { this.showSubScreen = true; this.editingConnectionProfile = connectionProfile; } closeSubView(): void { this.showSubScreen = false; this.showDeployNetwork = false; this.creatingIdCard = false; delete this.editingConnectionProfile; } createIdCard(): void { if (!this.usingLocally) { this.goLoginMain(); return; } this.showSubScreen = true; this.creatingIdCard = true; } finishedCardCreation(event) { if (event) { this.goLoginMain(); return this.loadIdentityCards(); } else { this.goLoginMain(); } } canDeploy(connectionProfileRef): boolean { return this.identityCardService.canDeploy(connectionProfileRef); } deployNetwork(connectionProfileRef): void { if (!this.canDeploy(connectionProfileRef)) { this.goLoginMain(); return; } let peerCardRef = this.identityCardService.getAdminCardRef(connectionProfileRef, IdentityCardService.peerAdminRole); this.identityCardService.setCurrentIdentityCard(peerCardRef); if (this.indestructibleCards.indexOf(peerCardRef) > -1) { this.showCredentials = false; } else { this.showCredentials = true; } this.showSubScreen = true; this.showDeployNetwork = true; } finishedDeploying(): Promise<void> { this.goLoginMain(); return this.loadIdentityCards(true); } importIdentity() { this.drawerService.open(ImportIdentityComponent).result.then((cardRef) => { this.alertService.successStatus$.next({ title: 'ID Card imported', text: 'The ID card ' + this.identityCardService.getIdentityCard(cardRef).getUserName() + ' was successfully imported', icon: '#icon-role_24' }); }).then(() => { return this.loadIdentityCards(); }).catch((reason) => { if (reason !== DrawerDismissReasons.ESC) { this.alertService.errorStatus$.next(reason); } }); } exportIdentity(cardRef): Promise<any> { let fileName; return this.identityCardService.getIdentityCardForExport(cardRef) .then((card) => { fileName = card.getUserName() + '.card'; return card.toArchive(); }) .then((archiveData) => { let file = new Blob([archiveData], {type: 'application/octet-stream'}); saveAs(file, fileName); }) .catch((reason) => { this.alertService.errorStatus$.next(reason); }); } removeIdentity(cardRef): void { let card = this.idCards.get(cardRef); let userId: string = card.getUserName(); const confirmModalRef = this.modalService.open(DeleteComponent); confirmModalRef.componentInstance.headerMessage = 'Remove ID Card'; confirmModalRef.componentInstance.fileName = userId; confirmModalRef.componentInstance.fileType = 'ID Card'; confirmModalRef.componentInstance.deleteMessage = 'Are you sure you want to do this?'; confirmModalRef.componentInstance.deleteFrom = 'My Wallet'; confirmModalRef.componentInstance.confirmButtonText = 'Remove'; confirmModalRef.result .then((result) => { if (result) { let deletePromise: Promise<void>; let cards = this.identityCardService.getAllCardsForBusinessNetwork(card.getBusinessNetworkName(), this.identityCardService.getQualifiedProfileName(card.getConnectionProfile())); if (card.getConnectionProfile()['x-type'] === 'web' && cards.size === 1) { deletePromise = this.adminService.connect(cardRef, card, true) .then(() => { this.alertService.busyStatus$.next({ title: 'Undeploying business network', force: true }); return this.adminService.undeploy(card.getBusinessNetworkName()); }); } else { deletePromise = Promise.resolve(); } return deletePromise .then(() => { return this.identityCardService.deleteIdentityCard(cardRef) .then(() => { this.alertService.busyStatus$.next(null); this.alertService.successStatus$.next({ title: 'ID Card Removed', text: 'The ID card was successfully removed from My Wallet.', icon: '#icon-bin_icon' }); return this.loadIdentityCards(); }); }) .catch((error) => { this.alertService.errorStatus$.next(error); }); } }, (reason) => { if (reason && reason !== 1) { this.alertService.errorStatus$.next(reason); } }); } sortIdCards(a, b): number { let cardA = this.identityCardService.getIdentityCard(a); let cardB = this.identityCardService.getIdentityCard(b); let aBusinessNetwork = cardA.getBusinessNetworkName(); let bBusinessNetwork = cardB.getBusinessNetworkName(); let aName = cardA.getUserName(); let bName = cardB.getUserName(); let aRoles = cardA.getRoles(); let bRoles = cardB.getRoles(); // sort by business network name let result = this.sortBy(aBusinessNetwork, bBusinessNetwork); if (result !== 0) { return result; } // then by role result = this.sortBy(aRoles, bRoles); if (result !== 0) { return result; } // then by name result = this.sortBy(aName, bName); } private sortBy(aName, bName): number { if (!aName && !bName) { return 0; } if (!aName && bName) { return -1; } if (aName && !bName) { return 1; } if (aName < bName) { return -1; } if (aName > bName) { return 1; } // they are equal return 0; } }
the_stack
import { ipcRenderer, remote } from 'electron'; import React, { Component } from 'react'; import { isEqual } from 'lodash'; import styles from './browser.css'; import { AddressBar } from '$Components/AddressBar'; import { TabBar } from '$Components/TabBar'; import { TabContents } from '$Components/TabContents'; // import { logger } from '$Logger'; import { extendComponent } from '$Utils/extendComponent'; import { wrapBrowserComponent } from '$Extensions/components'; import { handleNotifications, Notification } from '$Utils/handleNotificiations'; interface BrowserProps { address: string; bookmarks?: Array<any>; notifications: Array<Notification>; tabs: Record<string, unknown>; windows: Record<string, unknown>; history: Record<string, unknown>; windowId: any; addBookmark: ( ...args: Array<any> ) => any; removeBookmark: ( ...args: Array<any> ) => any; addWindow: ( ...args: Array<any> ) => any; addTabNext: ( ...args: Array<any> ) => any; addTabEnd: ( ...args: Array<any> ) => any; setActiveTab: ( ...args: Array<any> ) => any; windowCloseTab: ( ...args: Array<any> ) => any; reopenTab: ( ...args: Array<any> ) => any; closeWindow: ( ...args: Array<any> ) => any; showSettingsMenu: ( ...args: Array<any> ) => any; hideSettingsMenu: ( ...args: Array<any> ) => any; addTab: ( ...args: Array<any> ) => any; updateTabUrl: ( ...args: Array<any> ) => any; updateTabWebId: ( ...args: Array<any> ) => any; updateTabWebContentsId: ( ...args: Array<any> ) => any; toggleDevTools: ( ...args: Array<any> ) => any; tabShouldReload: ( ...args: Array<any> ) => any; updateTabTitle: ( ...args: Array<any> ) => any; updateTabFavicon: ( ...args: Array<any> ) => any; tabLoad: ( ...args: Array<any> ) => any; tabForwards: ( ...args: Array<any> ) => any; tabBackwards: ( ...args: Array<any> ) => any; focusWebview: ( ...args: Array<any> ) => any; blurAddressBar: ( ...args: Array<any> ) => any; selectAddressBar: ( ...args: Array<any> ) => any; deselectAddressBar: ( ...args: Array<any> ) => any; addNotification: ( ...args: Array<any> ) => any; updateNotification: ( ...args: Array<any> ) => any; clearNotification: ( ...args: Array<any> ) => any; } class Browser extends Component<BrowserProps, Record<string, unknown>> { static defaultProps = { addressBarIsSelected: false, tabs: {}, windows: {}, bookmarks: [], notifications: [] }; constructor( props ) { super( props ); this.state = {}; } componentDidMount() { const { addTab, addTabEnd, setActiveTab, windowCloseTab, reopenTab, clearNotification, tabForwards, tabBackwards } = this.props; // const addressBar = this.address; const body = document.querySelector( 'body' ); const div = document.createElement( 'div' ); div.setAttribute( 'class', 'no_display' ); div.setAttribute( 'id', 'link_revealer' ); body.append( div ); } static getDerivedStateFromProps( props, state ) { const { bookmarks, safeBrowserApp, tabs, windows, windowId } = props; const experimentsEnabled = safeBrowserApp ? safeBrowserApp.experimentsEnabled : false; // only show the first notification without a response. // TODO: Move windowId from state to store. const currentWindow = windows.openWindows[windowId] ? windows.openWindows[windowId] : {}; const windowsTabs = currentWindow && currentWindow.tabs ? currentWindow.tabs : []; const thisWindowOpenTabs = []; windowsTabs.forEach( ( tabId ) => { const aTab = tabs[tabId]; if ( !aTab || !aTab.url ) return; thisWindowOpenTabs.push( tabs[tabId] ); } ); const activeTabId = currentWindow && currentWindow.activeTab ? currentWindow.activeTab : undefined; const activeTab = activeTabId !== undefined ? tabs[activeTabId] : undefined; const activeTabAddress = activeTab ? activeTab.url : ''; const activeTabIsBookmarked = !!bookmarks.find( ( bookmark ) => bookmark.url === activeTabAddress ); const activeTabAddressIsSelected = tabs[activeTabId] ? tabs[activeTabId].ui.addressBarIsSelected : false; const { shouldFocusWebview } = activeTabId && tabs[activeTabId] ? tabs[activeTabId].ui.shouldFocusWebview : false; const settingsMenuIsVisible = currentWindow && currentWindow.ui && currentWindow.ui.settingsMenuIsVisible ? currentWindow.ui.settingsMenuIsVisible : false; return { activeTab, activeTabId, activeTabAddress, activeTabIsBookmarked, activeTabAddressIsSelected, openTabs: thisWindowOpenTabs, shouldFocusWebview, settingsMenuIsVisible, windowId, experimentsEnabled }; } componentDidUpdate = ( previousProperties ) => { const currentProperties = { ...this.props }; handleNotifications( previousProperties, currentProperties ); }; render() { const { props } = this; const { // history history, // bookmarks bookmarks, addBookmark, removeBookmark, // tabs tabs, updateTabUrl, updateTabWebId, updateTabWebContentsId, toggleDevTools, tabShouldReload, updateTabTitle, updateTabFavicon, tabLoad, tabForwards, selectAddressBar, deselectAddressBar, tabBackwards, focusWebview, blurAddressBar, // Notifications addNotification, updateNotification, // remove if not needed clearNotification, // remove if not needed // windows windows, addWindow, // remove if not needed setActiveTab, windowCloseTab, reopenTab, // remove if not needed closeWindow, // remove if not needed showSettingsMenu, hideSettingsMenu, // TODO extend tab to not need this safeBrowserApp } = props; const { activeTab, activeTabId, activeTabAddress, activeTabIsBookmarked, activeTabAddressIsSelected, shouldFocusWebview, settingsMenuIsVisible, windowId, openTabs, experimentsEnabled } = this.state; return ( <div className={styles.container}> <TabBar key={1} setActiveTab={setActiveTab} selectAddressBar={selectAddressBar} activeTabId={activeTabId} activeTab={activeTab} addTabNext={this.handleAddTabNext} addTabEnd={this.handleAddTabEnd} closeTab={this.handleCloseBrowserTab} tabs={openTabs} windows={windows} windowId={windowId} /> <AddressBar key={2} address={activeTabAddress} activeTab={activeTab} tabId={activeTabId} onSelect={deselectAddressBar} onFocus={selectAddressBar} updateTabUrl={updateTabUrl} setActiveTab={setActiveTab} onBlur={blurAddressBar} addBookmark={addBookmark} updateTabWebId={updateTabWebId} isBookmarked={activeTabIsBookmarked} addTabNext={this.handleAddTabNext} addTabEnd={this.handleAddTabEnd} removeBookmark={removeBookmark} hideSettingsMenu={hideSettingsMenu} showSettingsMenu={showSettingsMenu} settingsMenuIsVisible={settingsMenuIsVisible} isSelected={activeTabAddressIsSelected} tabBackwards={tabBackwards} tabForwards={tabForwards} tabShouldReload={tabShouldReload} windowId={windowId} focusWebview={focusWebview} ref={( c ) => { this.address = c; }} /> <TabContents key={4} tabBackwards={tabBackwards} focusWebview={focusWebview} shouldFocusWebview={shouldFocusWebview} closeTab={windowCloseTab} addTabNext={this.handleAddTabNext} addTabEnd={this.handleAddTabEnd} addNotification={addNotification} activeTabId={activeTabId} activeTab={activeTab} updateTabUrl={updateTabUrl} updateTabWebContentsId={updateTabWebContentsId} updateTabWebId={updateTabWebId} toggleDevTools={toggleDevTools} tabShouldReload={tabShouldReload} updateTabTitle={updateTabTitle} updateTabFavicon={updateTabFavicon} tabLoad={tabLoad} setActiveTab={setActiveTab} tabs={openTabs} allTabs={tabs} history={history} bookmarks={bookmarks} windowId={windowId} safeExperimentsEnabled={experimentsEnabled} ref={( c ) => { this.tabContents = c; }} /> </div> ); // TODO: if not, lets trigger close? } handleCloseBrowserTab = ( tab ) => { const { windows, windowCloseTab, windowId } = this.props; const currentWindow = windows.openWindows[windowId] ? windows.openWindows[windowId] : {}; const openTabIds = currentWindow.tabs; if ( openTabIds.length === 1 ) { ipcRenderer.send( 'command:close-window' ); } else { windowCloseTab( tab ); } }; handleAddTabEnd = ( tab ) => { const { addTabEnd, addTab, setActiveTab, windowId } = this.props; const { url, tabId } = tab; addTab( { url, tabId } ); addTabEnd( { windowId, tabId } ); setActiveTab( { windowId, tabId } ); }; handleAddTabNext = ( tab ) => { const { addTab, addTabEnd, setActiveTab, windowId, windows, addTabNext } = this.props; const { activeTabId } = this.state; const { tabId, url } = tab; addTab( { tabId, url } ); const currentWindow = windows.openWindows[windowId] ? windows.openWindows[windowId] : {}; const currentTabs = currentWindow !== {} ? currentWindow.tabs : []; const tabIndex = currentTabs.findIndex( ( element ) => element === activeTabId ); if ( tabIndex !== undefined ) { addTabNext( { tabId, tabIndex, windowId } ); } else { addTabEnd( { tabId, windowId } ); } setActiveTab( { tabId, windowId } ); }; } export const ExtendedBrowser = extendComponent( Browser, wrapBrowserComponent );
the_stack
import * as React from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import { unstable_composeClasses as composeClasses, useButton } from '@mui/base'; import { OverridableComponent } from '@mui/types'; import { unstable_capitalize as capitalize, unstable_useId as useId, unstable_useForkRef as useForkRef, } from '@mui/utils'; import { useThemeProps } from '../styles'; import styled from '../styles/styled'; import chipClasses, { getChipUtilityClass } from './chipClasses'; import { ChipProps, ChipTypeMap } from './ChipProps'; import ChipContext from './ChipContext'; const useUtilityClasses = ( ownerState: ChipProps & { focusVisible: boolean; clickable: boolean }, ) => { const { disabled, size, color, clickable, variant, focusVisible } = ownerState; const slots = { root: [ 'root', disabled && 'disabled', color && `color${capitalize(color)}`, size && `size${capitalize(size)}`, variant && `variant${capitalize(variant)}`, clickable && 'clickable', ], action: ['action', disabled && 'disabled', focusVisible && 'focusVisible'], label: ['label', size && `label${capitalize(size)}`], startDecorator: ['startDecorator'], endDecorator: ['endDecorator'], }; return composeClasses(slots, getChipUtilityClass, {}); }; const ChipRoot = styled('div', { name: 'JoyChip', slot: 'Root', overridesResolver: (props, styles) => styles.root, })<{ ownerState: ChipProps & { clickable: boolean } }>(({ theme, ownerState }) => { return [ { '--Chip-radius': '1.5rem', // for controlling chip delete margin offset '--Chip-decorator-childOffset': 'min(calc(var(--Chip-paddingInline) - (var(--Chip-minHeight) - 2 * var(--variant-borderWidth) - var(--Chip-decorator-childHeight)) / 2), var(--Chip-paddingInline))', '--internal-paddingBlock': 'max((var(--Chip-minHeight) - 2 * var(--variant-borderWidth) - var(--Chip-decorator-childHeight)) / 2, 0px)', '--Chip-decorator-childRadius': 'max((var(--Chip-radius) - var(--variant-borderWidth)) - var(--internal-paddingBlock), min(var(--internal-paddingBlock) / 2, (var(--Chip-radius) - var(--variant-borderWidth)) / 2))', '--Chip-delete-radius': 'var(--Chip-decorator-childRadius)', '--Chip-delete-size': 'var(--Chip-decorator-childHeight)', '--Avatar-radius': 'var(--Chip-decorator-childRadius)', '--Avatar-size': 'var(--Chip-decorator-childHeight)', '--Icon-margin': 'initial', // reset the icon's margin. '--internal-action-radius': 'var(--Chip-radius)', // to be used with Radio or Checkbox ...(ownerState.size === 'sm' && { '--Chip-gap': '0.25rem', '--Chip-paddingInline': '0.5rem', '--Chip-decorator-childHeight': 'calc(min(1.5rem, var(--Chip-minHeight)) - 2 * var(--variant-borderWidth))', '--Icon-fontSize': '0.875rem', '--Chip-minHeight': '1.5rem', fontSize: theme.vars.fontSize.xs, }), ...(ownerState.size === 'md' && { '--Chip-gap': '0.375rem', '--Chip-paddingInline': '0.75rem', '--Chip-decorator-childHeight': 'min(1.5rem, var(--Chip-minHeight))', '--Icon-fontSize': '1.125rem', '--Chip-minHeight': '2rem', fontSize: theme.vars.fontSize.sm, }), ...(ownerState.size === 'lg' && { '--Chip-gap': '0.5rem', '--Chip-paddingInline': '1rem', '--Chip-decorator-childHeight': 'min(2rem, var(--Chip-minHeight))', '--Icon-fontSize': '1.25rem', '--Chip-minHeight': '2.5rem', fontSize: theme.vars.fontSize.md, }), minHeight: 'var(--Chip-minHeight)', paddingInline: 'var(--Chip-paddingInline)', borderRadius: 'var(--Chip-radius)', position: 'relative', fontWeight: theme.vars.fontWeight.md, fontFamily: theme.vars.fontFamily.body, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', whiteSpace: 'nowrap', transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms', textDecoration: 'none', verticalAlign: 'middle', boxSizing: 'border-box', [`&.${chipClasses.disabled}`]: { color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}DisabledColor`], }, }, ...(!ownerState.clickable ? [ theme.variants[ownerState.variant!]?.[ownerState.color!], { [`&.${chipClasses.disabled}`]: theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!], }, ] : [ { '--variant-borderWidth': '0px', color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}Color`], }, ]), ]; }); const ChipLabel = styled('span', { name: 'JoyChip', slot: 'Label', overridesResolver: (props, styles) => styles.label, })<{ ownerState: ChipProps & { clickable: boolean } }>(({ ownerState }) => ({ display: 'inherit', alignItems: 'center', order: 1, flexGrow: 1, ...(ownerState.clickable && { zIndex: 1, pointerEvents: 'none', }), })); const ChipAction = styled('button', { name: 'JoyChip', slot: 'Action', overridesResolver: (props, styles) => styles.action, })<{ ownerState: ChipProps }>(({ theme, ownerState }) => [ { position: 'absolute', zIndex: 0, top: 0, left: 0, bottom: 0, right: 0, border: 'none', padding: 'initial', margin: 'initial', backgroundColor: 'initial', textDecoration: 'none', borderRadius: 'inherit', transition: 'background-color 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms', [theme.focus.selector]: theme.focus.default, }, theme.variants[ownerState.variant!]?.[ownerState.color!], { '&:hover': theme.variants[`${ownerState.variant!}Hover`]?.[ownerState.color!] }, { '&:active': theme.variants[`${ownerState.variant!}Active`]?.[ownerState.color!] }, { [`&.${chipClasses.disabled}`]: theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!], }, ]); const ChipStartDecorator = styled('span', { name: 'JoyChip', slot: 'StartDecorator', overridesResolver: (props, styles) => styles.startDecorator, })<{ ownerState: ChipProps & { clickable: boolean } }>({ '--Avatar-marginInlineStart': 'calc(var(--Chip-decorator-childOffset) * -1)', '--Chip-delete-margin': '0 0 0 calc(var(--Chip-decorator-childOffset) * -1)', '--Icon-margin': '0 0 0 calc(var(--Chip-paddingInline) / -4)', display: 'inherit', marginInlineEnd: 'var(--Chip-gap)', // set zIndex to 1 with order to stay on top of other controls, eg. Checkbox, Radio order: 0, zIndex: 1, pointerEvents: 'none', }); const ChipEndDecorator = styled('span', { name: 'JoyChip', slot: 'EndDecorator', overridesResolver: (props, styles) => styles.endDecorator, })<{ ownerState: ChipProps & { clickable: boolean } }>({ '--Chip-delete-margin': '0 calc(var(--Chip-decorator-childOffset) * -1) 0 0', '--Icon-margin': '0 calc(var(--Chip-paddingInline) / -4) 0 0', display: 'inherit', marginInlineStart: 'var(--Chip-gap)', // set zIndex to 1 with order to stay on top of other controls, eg. Checkbox, Radio order: 2, zIndex: 1, pointerEvents: 'none', }); /** * Chips represent complex entities in small blocks, such as a contact. */ const Chip = React.forwardRef(function Chip(inProps, ref) { const props = useThemeProps<typeof inProps & ChipProps>({ props: inProps, name: 'JoyChip' }); const { children, className, componentsProps = {}, color = 'primary', component, onClick, disabled = false, size = 'md', variant = 'solid', startDecorator, endDecorator, ...other } = props; const { component: actionComponent, ...actionProps } = componentsProps.action || {}; const clickable = !!onClick || !!componentsProps.action; const id = useId(componentsProps.action?.id); const actionRef = React.useRef<HTMLElement | null>(null); const handleActionRef = useForkRef(actionRef, actionProps.ref); const { focusVisible, getRootProps } = useButton({ disabled, ...actionProps, ref: handleActionRef, }); const ownerState = { ...props, component, onClick, disabled, focusVisible, size, color, clickable, variant, }; const classes = useUtilityClasses(ownerState); return ( <ChipContext.Provider value={{ disabled, variant, color }}> <ChipRoot as={component} className={clsx(classes.root, className)} ref={ref} ownerState={ownerState} {...other} > {clickable && ( <ChipAction aria-labelledby={id} {...actionProps} // @ts-expect-error getRootProps typings should be fixed. {...getRootProps({ onClick, ...actionProps })} as={actionComponent} className={clsx(classes.action, actionProps.className)} ownerState={ownerState} /> )} {/* label is always the first element for integrating with other controls, eg. Checkbox, Radio. Use CSS order to rearrange position */} <ChipLabel id={id} {...componentsProps.label} className={clsx(classes.label, componentsProps.label?.className)} ownerState={ownerState} > {children} </ChipLabel> {startDecorator && ( <ChipStartDecorator {...componentsProps.startDecorator} className={clsx(classes.startDecorator, componentsProps.startDecorator?.className)} ownerState={ownerState} > {startDecorator} </ChipStartDecorator> )} {endDecorator && ( <ChipEndDecorator {...componentsProps.endDecorator} className={clsx(classes.endDecorator, componentsProps.endDecorator?.className)} ownerState={ownerState} > {endDecorator} </ChipEndDecorator> )} </ChipRoot> </ChipContext.Provider> ); }) as OverridableComponent<ChipTypeMap>; Chip.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit TypeScript types and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([ PropTypes.oneOf(['danger', 'info', 'neutral', 'primary', 'success', 'warning']), PropTypes.string, ]), /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * The props used for each slot inside the Input. * @default {} */ componentsProps: PropTypes.shape({ action: PropTypes.object, endDecorator: PropTypes.object, label: PropTypes.object, root: PropTypes.object, startDecorator: PropTypes.object, }), /** * If `true`, the component is disabled. * @default false */ disabled: PropTypes.bool, /** * Element placed after the children. */ endDecorator: PropTypes.node, /** * @ignore */ onClick: PropTypes.func, /** * The size of the component. * It accepts theme values between 'sm' and 'lg'. * @default 'md' */ size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([ PropTypes.oneOf(['lg', 'md', 'sm']), PropTypes.string, ]), /** * Element placed before the children. */ startDecorator: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object, ]), /** * The variant to use. * @default 'solid' */ variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([ PropTypes.oneOf(['outlined', 'plain', 'soft', 'solid']), PropTypes.string, ]), } as any; export default Chip;
the_stack
import { useState, HTMLProps, HTMLAttributes, KeyboardEvent } from 'react'; import { composeEventHandlers } from '@zendeskgarden/container-utilities'; const GRID_KEYS = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End']; export interface IUseGridProps { /** Determines if navigation uses right-to-left direction */ rtl?: boolean; /** Enables wrapped keyboard navigation */ wrap?: boolean; /** Enables cell selection */ selection?: boolean; /** Sets the two-dimension array to render the grid */ matrix: any[][]; /** Prefixes IDs for the grid and cells */ idPrefix?: string; /** Sets the focused row index in a controlled grid */ rowIndex?: number; /** Sets the focused column index in a controlled grid */ colIndex?: number; /** Sets the selected row index in a controlled grid */ selectedRowIndex?: number; /** Sets the selected column index in a controlled grid */ selectedColIndex?: number; /** Sets the default focused row index in a uncontrolled grid */ defaultRowIndex?: number; /** Sets the default focused column index in a uncontrolled grid */ defaultColIndex?: number; /** Sets the default selected row index in a uncontrolled grid */ defaultSelectedRowIndex?: number; /** Sets the default selected column index in a uncontrolled grid */ defaultSelectedColIndex?: number; /** Handles grid change event */ onChange?: (rowIndex: number, colIndex: number) => void; /** Handles grid select event */ onSelect?: (rowIndex: number, colIndex: number) => void; } interface IGetGridCellProps extends HTMLProps<any> { rowIdx: number; colIdx: number; } export interface IUseGridReturnValue { getGridCellProps: (options: IGetGridCellProps) => HTMLAttributes<any>; } export function useGrid({ rtl, wrap, matrix, idPrefix, selection, onChange, onSelect, rowIndex, colIndex, selectedRowIndex, selectedColIndex, defaultRowIndex, defaultColIndex, defaultSelectedRowIndex, defaultSelectedColIndex }: IUseGridProps): IUseGridReturnValue { const rowCount = matrix.length; const columnCount = matrix[0].length; const lastRowLength = matrix[rowCount - 1].length; const [uncontrolledRowIndex, setUncontrolledRowIndex] = useState( defaultRowIndex !== null && defaultRowIndex !== undefined ? defaultRowIndex : 0 ); const [uncontrolledColIndex, setUncontrolledColIndex] = useState( defaultColIndex !== null && defaultColIndex !== undefined ? defaultColIndex : 0 ); const controlledFocus = rowIndex !== null && colIndex !== null && rowIndex !== undefined && colIndex !== undefined; const controlledSelect = selectedRowIndex !== null && selectedColIndex !== null && selectedRowIndex !== undefined && selectedColIndex !== undefined; const [uncontrolledSelectedRowIndex, setUncontrolledSelectedIndex] = useState( defaultSelectedRowIndex !== null && defaultSelectedRowIndex !== undefined ? defaultSelectedRowIndex : -1 ); const [uncontrolledSelectedColIndex, setUncontrolledSelectedColIndex] = useState( defaultSelectedColIndex !== null && defaultSelectedColIndex !== undefined ? defaultSelectedColIndex : -1 ); const isControlled = controlledFocus || controlledSelect; const setFocusedCell = (rowIdx: number, colIdx: number) => { setUncontrolledRowIndex(rowIdx); setUncontrolledColIndex(colIdx); }; const setSelectedCell = (rowIdx: number, colIdx: number) => { setUncontrolledSelectedIndex(rowIdx); setUncontrolledSelectedColIndex(colIdx); }; const setFocus = (rowIdx: number, colIdx: number) => { const id = `${idPrefix}-${rowIdx}-${colIdx}`; const element = document.getElementById(id); element && element.focus(); }; const onNavigate = (e: KeyboardEvent<HTMLElement>) => { if (GRID_KEYS.includes(e.key)) { e.preventDefault(); } if (isControlled) { const onLastRow = rowIndex === rowCount - 1; const onLastCol = colIndex === columnCount - 1; const rightEnd = onLastRow && colIndex === lastRowLength - 1; const downEnd = rowIndex === rowCount - 2 && (colIndex as number) >= lastRowLength; const backward = () => { if ((colIndex as number) > 0) { onChange && onChange(rowIndex as number, (colIndex as number) - 1); setFocus(rowIndex as number, (colIndex as number) - 1); } if (wrap && colIndex === 0 && (rowIndex as number) > 0) { onChange && onChange((rowIndex as number) - 1, columnCount - 1); setFocus((rowIndex as number) - 1, columnCount - 1); } }; const forward = () => { if ((colIndex as number) < columnCount - 1 && !rightEnd) { onChange && onChange(rowIndex as number, (colIndex as number) + 1); setFocus(rowIndex as number, (colIndex as number) + 1); } if (wrap && onLastCol && !onLastRow) { onChange && onChange((rowIndex as number) + 1, 0); setFocus((rowIndex as number) + 1, 0); } }; switch (e.key) { case 'ArrowLeft': return rtl ? forward() : backward(); case 'ArrowRight': return rtl ? backward() : forward(); case 'ArrowUp': if (rowIndex === 0 && colIndex === 0) { break; } if ((rowIndex as number) > 0) { onChange && onChange((rowIndex as number) - 1, colIndex as number); setFocus((rowIndex as number) - 1, colIndex as number); break; } if (wrap) { if ((colIndex as number) <= lastRowLength) { setFocus(rowCount - 1, (colIndex as number) - 1); onChange && onChange(rowCount - 1, (colIndex as number) - 1); } else { setFocus(rowCount - 2, (colIndex as number) - 1); onChange && onChange(rowCount - 2, (colIndex as number) - 1); } } break; case 'ArrowDown': if ((rowIndex as number) < rowCount - 1 && !downEnd) { onChange && onChange((rowIndex as number) + 1, colIndex as number); setFocus((rowIndex as number) + 1, colIndex as number); } if (wrap) { if ((colIndex as number) < columnCount - 1 && onLastRow) { setFocus(0, (colIndex as number) + 1); onChange && onChange(0, (colIndex as number) + 1); } if ( (colIndex as number) >= lastRowLength && rowCount - 1 === (rowIndex as number) + 1 && (colIndex as number) < columnCount - 1 ) { setFocus(0, (colIndex as number) + 1); onChange && onChange(0, (colIndex as number) + 1); break; } } break; case 'Home': if (e.ctrlKey) { onChange && onChange(0, 0); setFocus(0, 0); } else { onChange && onChange(rowIndex as number, 0); setFocus(rowIndex as number, 0); } break; case 'End': if (e.ctrlKey) { onChange && onChange(rowCount - 1, matrix[rowCount - 1].length - 1); setFocus(rowCount - 1, matrix[rowCount - 1].length - 1); } else { onChange && onChange(rowIndex as number, matrix[rowIndex as number].length - 1); setFocus(rowIndex as number, matrix[rowIndex as number].length - 1); } break; default: } } else { const onLastRow = uncontrolledRowIndex === rowCount - 1; const onLastCol = uncontrolledColIndex === columnCount - 1; const rightEnd = onLastRow && uncontrolledColIndex === lastRowLength - 1; const downEnd = uncontrolledRowIndex === rowCount - 2 && uncontrolledColIndex >= lastRowLength; const forward = () => { if (uncontrolledColIndex < columnCount - 1 && !rightEnd) { setUncontrolledColIndex(uncontrolledColIndex + 1); setFocus(uncontrolledRowIndex, uncontrolledColIndex + 1); onChange && onChange(uncontrolledRowIndex, uncontrolledColIndex + 1); } if (wrap && onLastCol && !onLastRow) { setUncontrolledRowIndex(uncontrolledRowIndex + 1); setUncontrolledColIndex(0); setFocus(uncontrolledRowIndex + 1, 0); onChange && onChange(uncontrolledRowIndex + 1, 0); } }; const backward = () => { if (uncontrolledColIndex > 0) { setUncontrolledColIndex(uncontrolledColIndex - 1); setFocus(uncontrolledRowIndex, uncontrolledColIndex - 1); onChange && onChange(uncontrolledRowIndex, uncontrolledColIndex - 1); } if (wrap && uncontrolledColIndex === 0 && uncontrolledRowIndex > 0) { setUncontrolledRowIndex(uncontrolledRowIndex - 1); setUncontrolledColIndex(columnCount - 1); setFocus(uncontrolledRowIndex - 1, columnCount - 1); onChange && onChange(uncontrolledRowIndex - 1, columnCount - 1); } }; switch (e.key) { case 'ArrowLeft': return rtl ? forward() : backward(); case 'ArrowRight': return rtl ? backward() : forward(); case 'ArrowUp': if (uncontrolledRowIndex === 0 && uncontrolledColIndex === 0) { break; } if (uncontrolledRowIndex > 0) { setUncontrolledRowIndex(uncontrolledRowIndex - 1); setFocus(uncontrolledRowIndex - 1, uncontrolledColIndex); onChange && onChange(uncontrolledRowIndex - 1, uncontrolledColIndex); break; } if (wrap) { if (uncontrolledColIndex <= lastRowLength) { setUncontrolledRowIndex(rowCount - 1); setUncontrolledColIndex(uncontrolledColIndex - 1); setFocus(rowCount - 1, uncontrolledColIndex - 1); onChange && onChange(rowCount - 1, uncontrolledColIndex - 1); } else { setUncontrolledRowIndex(rowCount - 2); setUncontrolledColIndex(uncontrolledColIndex - 1); setFocus(rowCount - 2, uncontrolledColIndex - 1); onChange && onChange(rowCount - 2, uncontrolledColIndex - 1); } } break; case 'ArrowDown': if (uncontrolledRowIndex < rowCount - 1 && !downEnd) { setUncontrolledRowIndex(uncontrolledRowIndex + 1); setFocus(uncontrolledRowIndex + 1, uncontrolledColIndex); onChange && onChange(uncontrolledRowIndex + 1, uncontrolledColIndex); } if (wrap) { if (uncontrolledColIndex < columnCount - 1 && onLastRow) { setUncontrolledRowIndex(0); setUncontrolledColIndex(uncontrolledColIndex + 1); setFocus(0, uncontrolledColIndex + 1); onChange && onChange(0, uncontrolledColIndex + 1); } if ( uncontrolledColIndex >= lastRowLength && rowCount - 1 === uncontrolledRowIndex + 1 && uncontrolledColIndex < columnCount - 1 ) { setUncontrolledRowIndex(0); setUncontrolledColIndex(uncontrolledColIndex + 1); setFocus(0, uncontrolledColIndex + 1); onChange && onChange(0, uncontrolledColIndex + 1); break; } } break; case 'Home': if (e.ctrlKey) { setFocusedCell(0, 0); setFocus(0, 0); onChange && onChange(0, 0); } else { setFocusedCell(uncontrolledRowIndex, 0); setFocus(uncontrolledRowIndex, 0); onChange && onChange(uncontrolledRowIndex, 0); } break; case 'End': if (e.ctrlKey) { setFocusedCell(rowCount - 1, lastRowLength - 1); setFocus(rowCount - 1, lastRowLength - 1); onChange && onChange(rowCount - 1, lastRowLength - 1); } else { setFocusedCell(uncontrolledRowIndex, matrix[uncontrolledRowIndex].length - 1); setFocus(uncontrolledRowIndex, matrix[uncontrolledRowIndex].length - 1); onChange && onChange(uncontrolledRowIndex, matrix[uncontrolledRowIndex].length - 1); } break; default: } } return undefined; }; const getTabIndex = (rowIdx: number, colIdx: number) => { if (isControlled) { if (rowIndex === -1 && colIndex === -1 && rowIdx === 0 && colIdx === 0) { return 0; } return rowIndex === rowIdx && colIndex === colIdx ? 0 : -1; } if (rowIdx <= 0 && colIdx <= 0 && uncontrolledRowIndex <= 0 && uncontrolledColIndex <= 0) { return 0; } return uncontrolledRowIndex === rowIdx && uncontrolledColIndex === colIdx ? 0 : -1; }; const getAriaSelected = (rowIdx: number, colIdx: number) => { let ariaSelected; if (isControlled) { ariaSelected = selectedRowIndex === rowIdx && selectedColIndex === colIdx; } else { ariaSelected = uncontrolledSelectedRowIndex === rowIdx && uncontrolledSelectedColIndex === colIdx; } return ariaSelected; }; const getGridCellProps = ({ rowIdx, colIdx, onClick, onFocus, onKeyDown, ...other }: IGetGridCellProps) => { return { tabIndex: getTabIndex(rowIdx, colIdx), role: 'gridcell', 'aria-selected': selection ? getAriaSelected(rowIdx, colIdx) : undefined, id: `${idPrefix}-${rowIdx}-${colIdx}`, onClick: composeEventHandlers(onClick, () => { if (isControlled === false) { setFocusedCell(rowIdx, colIdx); selection && setSelectedCell(rowIdx, colIdx); } onChange && onChange(rowIdx, colIdx); selection && onSelect && onSelect(rowIdx, colIdx); }), onFocus: composeEventHandlers(onFocus, () => { if (isControlled) { rowIndex === -1 && colIndex === -1 && onChange && onChange(0, 0); } }), onKeyDown: composeEventHandlers(onKeyDown, onNavigate), ...other }; }; return { getGridCellProps }; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a logz Monitor. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleLogzMonitor = new azure.monitoring.LogzMonitor("exampleLogzMonitor", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * plan: { * billingCycle: "Monthly", * effectiveDate: "2022-06-06T00:00:00Z", * planId: "100gb14days", * usageType: "Committed", * }, * user: { * email: "user@example.com", * firstName: "Example", * lastName: "User", * phoneNumber: "+12313803556", * }, * }); * ``` * * ## Import * * logz Monitors can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:monitoring/logzMonitor:LogzMonitor example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Logz/monitors/monitor1 * ``` */ export class LogzMonitor extends pulumi.CustomResource { /** * Get an existing LogzMonitor 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?: LogzMonitorState, opts?: pulumi.CustomResourceOptions): LogzMonitor { return new LogzMonitor(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:monitoring/logzMonitor:LogzMonitor'; /** * Returns true if the given object is an instance of LogzMonitor. 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 LogzMonitor { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LogzMonitor.__pulumiType; } /** * Name of the Logz organization. Changing this forces a new logz Monitor to be created. */ public readonly companyName!: pulumi.Output<string | undefined>; /** * Whether the resource monitoring is enabled? */ public readonly enabled!: pulumi.Output<boolean | undefined>; /** * The ID of the Enterprise App. Changing this forces a new logz Monitor to be created. */ public readonly enterpriseAppId!: pulumi.Output<string | undefined>; /** * The Azure Region where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ public readonly location!: pulumi.Output<string>; /** * The ID associated with the logz organization of this logz Monitor. */ public /*out*/ readonly logzOrganizationId!: pulumi.Output<string>; /** * The name which should be used for this logz Monitor. Changing this forces a new logz Monitor to be created. */ public readonly name!: pulumi.Output<string>; /** * A `plan` block as defined below. */ public readonly plan!: pulumi.Output<outputs.monitoring.LogzMonitorPlan>; /** * The name of the Resource Group where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The single sign on url associated with the logz organization of this logz Monitor. */ public /*out*/ readonly singleSignOnUrl!: pulumi.Output<string>; /** * A mapping of tags which should be assigned to the logz Monitor. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A `user` block as defined below. */ public readonly user!: pulumi.Output<outputs.monitoring.LogzMonitorUser>; /** * Create a LogzMonitor 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: LogzMonitorArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LogzMonitorArgs | LogzMonitorState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LogzMonitorState | undefined; inputs["companyName"] = state ? state.companyName : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["enterpriseAppId"] = state ? state.enterpriseAppId : undefined; inputs["location"] = state ? state.location : undefined; inputs["logzOrganizationId"] = state ? state.logzOrganizationId : undefined; inputs["name"] = state ? state.name : undefined; inputs["plan"] = state ? state.plan : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["singleSignOnUrl"] = state ? state.singleSignOnUrl : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["user"] = state ? state.user : undefined; } else { const args = argsOrState as LogzMonitorArgs | undefined; if ((!args || args.plan === undefined) && !opts.urn) { throw new Error("Missing required property 'plan'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.user === undefined) && !opts.urn) { throw new Error("Missing required property 'user'"); } inputs["companyName"] = args ? args.companyName : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["enterpriseAppId"] = args ? args.enterpriseAppId : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["plan"] = args ? args.plan : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["user"] = args ? args.user : undefined; inputs["logzOrganizationId"] = undefined /*out*/; inputs["singleSignOnUrl"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LogzMonitor.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LogzMonitor resources. */ export interface LogzMonitorState { /** * Name of the Logz organization. Changing this forces a new logz Monitor to be created. */ companyName?: pulumi.Input<string>; /** * Whether the resource monitoring is enabled? */ enabled?: pulumi.Input<boolean>; /** * The ID of the Enterprise App. Changing this forces a new logz Monitor to be created. */ enterpriseAppId?: pulumi.Input<string>; /** * The Azure Region where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ location?: pulumi.Input<string>; /** * The ID associated with the logz organization of this logz Monitor. */ logzOrganizationId?: pulumi.Input<string>; /** * The name which should be used for this logz Monitor. Changing this forces a new logz Monitor to be created. */ name?: pulumi.Input<string>; /** * A `plan` block as defined below. */ plan?: pulumi.Input<inputs.monitoring.LogzMonitorPlan>; /** * The name of the Resource Group where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The single sign on url associated with the logz organization of this logz Monitor. */ singleSignOnUrl?: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the logz Monitor. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `user` block as defined below. */ user?: pulumi.Input<inputs.monitoring.LogzMonitorUser>; } /** * The set of arguments for constructing a LogzMonitor resource. */ export interface LogzMonitorArgs { /** * Name of the Logz organization. Changing this forces a new logz Monitor to be created. */ companyName?: pulumi.Input<string>; /** * Whether the resource monitoring is enabled? */ enabled?: pulumi.Input<boolean>; /** * The ID of the Enterprise App. Changing this forces a new logz Monitor to be created. */ enterpriseAppId?: pulumi.Input<string>; /** * The Azure Region where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ location?: pulumi.Input<string>; /** * The name which should be used for this logz Monitor. Changing this forces a new logz Monitor to be created. */ name?: pulumi.Input<string>; /** * A `plan` block as defined below. */ plan: pulumi.Input<inputs.monitoring.LogzMonitorPlan>; /** * The name of the Resource Group where the logz Monitor should exist. Changing this forces a new logz Monitor to be created. */ resourceGroupName: pulumi.Input<string>; /** * A mapping of tags which should be assigned to the logz Monitor. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `user` block as defined below. */ user: pulumi.Input<inputs.monitoring.LogzMonitorUser>; }
the_stack
import React, { Component } from 'react' import { StyleSheet, View, Image, BackHandler, Dimensions, TouchableNativeFeedback, KeyboardAvoidingView, InteractionManager, Keyboard, TextInput, Animated, StatusBar, Platform } from 'react-native' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, accentColor } from '../constant/colorConfig' let AnimatedKeyboardAvoidingView = Animated.createAnimatedComponent(KeyboardAvoidingView) let screen = Dimensions.get('window') let { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = screen SCREEN_HEIGHT = SCREEN_HEIGHT - (StatusBar.currentHeight || 0) + 1 let CIRCLE_SIZE = 56 let backConfig = { tension: 30, friction: 7 } const isIOS = Platform.OS === 'ios' const method = isIOS ? 'timing' : 'spring' const duration = isIOS ? { duration: 200 } : {} export default class Search extends Component<any, any> { constructor(props) { super(props) const { params } = this.props.navigation.state this.state = { icon: false, content: params.content || '', openVal: new Animated.Value(0), marginTop: new Animated.Value(0), toolbarOpenVal: new Animated.Value(0), placeholder: params.placeholder || '搜索标题' } } componentDidMount() { Animated[method](this.state.openVal, { toValue: 1, ...duration }).start() } _pressBack = (callback) => { const { openVal } = this.state // Keyboard.dismiss() Animated[method](openVal, { toValue: 0, ...backConfig, ...duration }).start(() => { const _lastNativeText = this.content._lastNativeText this.props.navigation.goBack() InteractionManager.runAfterInteractions(() => { typeof callback === 'function' && callback(_lastNativeText) Keyboard.dismiss() }) }) } isKeyboardShowing = false keyboardDidHideListener: any = false keyboardDidShowListener: any = false removeListener: any = false isToolbarShowing: any = false componentWillUnmount() { this.keyboardDidHideListener.remove() this.keyboardDidShowListener.remove() this.removeListener && this.removeListener.remove() } async componentWillMount() { const { openVal } = this.state const { modeInfo } = this.props.screenProps this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => { this.isKeyboardShowing = true }) this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => { this.isKeyboardShowing = false }) this.isToolbarShowing = false this.removeListener = BackHandler.addEventListener('hardwareBackPress', () => { Animated[method](openVal, { toValue: 0, ...backConfig, ...duration }).start(() => { this.props.navigation.goBack() Keyboard.dismiss() }) return true }) const icon = await Promise.all([ Ionicons.getImageSource('md-arrow-back', 20, modeInfo.standardColor), Ionicons.getImageSource('md-search', 20, modeInfo.standardColor) ]) this.setState({ icon: { backIcon: icon[0], sendIcon: icon[1] } }) } _onSubmitEditing = () => { const { callback } = this.props.navigation.state.params // console.log(event.nativeEvent, event.nativeEvent.text) this._pressBack(callback) } ref: any = null render() { let { openVal, marginTop } = this.state const { icon } = this.state const { modeInfo } = this.props.screenProps const { callback } = this.props.navigation.state.params const searchHeight = 40 let animatedStyle = { left: openVal.interpolate({ inputRange: [0, 1], outputRange: [SCREEN_WIDTH, 0] }), bottom: openVal.interpolate({ inputRange: [0, 1], outputRange: [SCREEN_HEIGHT, 0] }), borderWidth: 0, backgroundColor: modeInfo.backgroundColor, borderRadius: openVal.interpolate({ inputRange: [-0.15, 0, 1], outputRange: [CIRCLE_SIZE * 1.3, CIRCLE_SIZE * 1.3, 0] }), // backgroundColor: openVal.interpolate({ // inputRange: [0, 1], // outputRange: [accentColor, modeInfo.backgroundColor] // }), marginTop: marginTop.interpolate({ inputRange: [0, SCREEN_HEIGHT], outputRange: [0, SCREEN_HEIGHT] }) } let animatedToolbarStyle = { height: openVal.interpolate({ inputRange: [0, 0.9, 1], outputRange: [searchHeight, searchHeight, searchHeight] }), borderWidth: 0, backgroundColor: modeInfo.backgroundColor // borderRadius: openVal.interpolate({ inputRange: [-0.15, 0, 1], outputRange: [CIRCLE_SIZE * 1.3, CIRCLE_SIZE * 1.3, 0] }), // zIndex: openVal.interpolate({ inputRange: [0, 1], outputRange: [0, 3] }), // backgroundColor: openVal.interpolate({ // inputRange: [0, 1], // outputRange: [accentColor, modeInfo.backgroundColor] // }), } return ( <Animated.View ref={ref => this.ref = ref} style={[ styles.circle, styles.open, animatedStyle, { top: StatusBar.currentHeight || 24, right: 0, backgroundColor: 'rgba(0,0,0,0.251)', padding: 6, borderBottomLeftRadius: openVal.interpolate({ inputRange: [0, 9 / 16, 1], outputRange: [SCREEN_HEIGHT / 2, SCREEN_HEIGHT / 2, 0] }) } ]} > <Animated.View style={[styles.KeyboardAvoidingView, { height: searchHeight, flexDirection: 'row', borderRadius: 4 }]} > <Animated.View style={[styles.toolbar, animatedToolbarStyle, { alignItems: 'center', justifyContent: 'center', borderBottomLeftRadius: 4, borderTopLeftRadius: 4 }]}> <View style={{ height: searchHeight, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}> <TouchableNativeFeedback onPress={this._pressBack} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: searchHeight / 2 }} > <View style={{ width: searchHeight, height: searchHeight, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.backIcon} style={{ width: 15, height: 15, alignSelf: 'center', alignContent: 'center'}} />} </View> </TouchableNativeFeedback> </View> </Animated.View > <AnimatedKeyboardAvoidingView behavior={'padding'} style={[styles.contentView, { height: searchHeight, justifyContent: 'center', alignContent: 'center' }]}> <TextInput placeholder={this.state.placeholder} autoCorrect={false} multiline={false} keyboardType='default' returnKeyType='go' returnKeyLabel='go' blurOnSubmit={true} onSubmitEditing={this._onSubmitEditing} ref={ref => this.content = ref} onChange={({ nativeEvent }) => { this.setState({ content: nativeEvent.text }) }} value={this.state.content} style={[styles.textInput, { color: modeInfo.titleTextColor, textAlign: 'left', textAlignVertical: 'top', flex: 1, backgroundColor: modeInfo.backgroundColor }]} placeholderTextColor={modeInfo.standardTextColor} // underlineColorAndroid={accentColor} underlineColorAndroid='rgba(0,0,0,0)' /> </AnimatedKeyboardAvoidingView> <Animated.View style={[styles.toolbar, animatedToolbarStyle, { alignItems: 'center', justifyContent: 'center', height: searchHeight, borderTopRightRadius: 4, borderBottomRightRadius: 4 }]}> <View style={{ height: searchHeight, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}> <TouchableNativeFeedback onPress={() => this._pressBack(callback)} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: searchHeight / 2 }} > <View style={{ width: searchHeight, height: searchHeight, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.sendIcon} style={{ width: 15, height: 15, alignSelf: 'center', alignContent: 'center'}} />} </View> </TouchableNativeFeedback> </View> </Animated.View > </Animated.View> </Animated.View> ) } } const styles = StyleSheet.create({ circle: { flex: 1, position: 'absolute', backgroundColor: 'white', width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, borderWidth: 2, borderColor: accentColor // elevation: 12, }, open: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, width: undefined, // unset value from styles.circle height: undefined, // unset value from styles.circle borderRadius: CIRCLE_SIZE / 2 // unset value from styles.circle }, toolbar: { backgroundColor: standardColor, height: 56, // elevation: 4, flex: -1 }, mainFont: { fontSize: 15, color: accentColor }, textInput: { fontSize: 15 }, KeyboardAvoidingView: { flex: 10, // width: width, flexDirection: 'column' }, titleView: { flex: 1, justifyContent: 'center' // flexDirection: 'column', // justifyContent: 'space-between', }, isPublicView: { flex: 1, flexDirection: 'row', // flexDirection: 'column', alignItems: 'center' }, contentView: { flex: 12 // flexDirection: 'column', }, submit: { // flex: -1, // height: 20, // //margin: 10, // marginTop: 30, // marginBottom: 20, }, submitButton: { // backgroundColor: accentColor, // height: 40, // alignItems: 'center', // justifyContent: 'center', }, regist: { flex: 1, flexDirection: 'row', marginTop: 20, margin: 10 }, openURL: { color: accentColor, textDecorationLine: 'underline' } })
the_stack
import * as adBlocker from "./lib/adBlocker"; import {IGenericObject, Intent, IRuntimeMessage, IRuntimeResponse, Settings} from "./lib/common"; import * as dlAll from "./lib/download_all/core"; import * as mal from "./lib/MyAnimeList/core"; import * as recentlyWatched from "./lib/recently_watched"; import RedditDiscussion from "./lib/reddit_discussion"; import {cleanAnimeName, joinURL, loadSettings, obj2query} from "./lib/utils"; export type SendResponse = (param: IRuntimeResponse) => void; /* --- Initialize other background services --- */ adBlocker.setup(); /*** * This is the background listener. It listens to the messages sent * by content script and friends and act accordingly. It also sends * out messages to tabs/content scripts when required. */ chrome.runtime.onMessage.addListener((message: IRuntimeMessage, sender, sendResponse: SendResponse) => { // Probably a validation for whether the required // object properties are present or missing? switch (message.intent) { case Intent.AdBlocker_Disable: adBlocker.disableAdblocker(); break; case Intent.AdBlocker_Enable: adBlocker.enableAdblocker(); break; case Intent.AdBlocker_UpdateFilter_Local: adBlocker .updateViaLocal(message.filterList) .then(() => sendResponse({ success: true, })); return true; /**************************************************************************************************************/ case Intent.Download_All: let setupOptions = { animeName: message.animeName, method: message.method, quality: message.quality, selectedEpisodes: message.selectedEpisodes, sender, server: message.server, serverId: message.serverId, ts: message.ts, }; dlAll.start(message.baseUrl, setupOptions); break; /**************************************************************************************************************/ case Intent.Reddit_Discussion: let redditSearchUrl = new RedditDiscussion(message.animeName, message.episode, message.altNames).url(); chrome.tabs.create({ url: redditSearchUrl, }); break; case Intent.Find_In_Mal: chrome.tabs.create({ url: "https://myanimelist.net/anime.php?q=" + cleanAnimeName(message.animeName), }); break; case Intent.Find_In_Kitsu: chrome.tabs.create({ url: "https://kitsu.io/anime?text=" + cleanAnimeName(message.animeName), }); break; case Intent.Search_Anime: let params = { keyword: message.searchText, sort: "year A", }; let endpoint = message.baseUrl + "/ajax/film/search?" + obj2query(params); fetch(endpoint) .then(response => { if (response.ok) { return response.json(); } throw new Error(response.status.toString()); }) .then(resp => sendResponse({ data: resp, success: true, })) .catch(() => sendResponse({ success: false, })); return true; /**************************************************************************************************************/ case Intent.Open_Options: // TODO: should only 1 settings page be allowed open at a time // The way this works is, if message.params is not present the // url to open is url of "dashboard.html". If message.params is // present, the url to open is same as above with the search // params added to it. let url = chrome.runtime.getURL("dashboard.html"); if (message.params && typeof message.params === "object") { url = joinURL(url, message.params); } chrome.tabs.create({ url, }); break; /**************************************************************************************************************/ case Intent.Recently_Watched_Add: recentlyWatched.addToList({ animeId: message.animeId, animeName: message.animeName, epId: message.epId, epNum: message.epNum, timestamp: new Date().toISOString(), url: message.url, }); break; case Intent.Recently_Watched_List: sendResponse({ data: recentlyWatched.getList(), success: true, }); break; case Intent.Recently_Watched_Remove: let isRemoved = recentlyWatched.removeFromList(message.animeId); let count = recentlyWatched.listCount(); sendResponse({ data: count, success: isRemoved, }); break; /**************************************************************************************************************/ case Intent.MAL_QuickAdd: mal .quickAdd(message.animeId) .then(() => sendResponse({ success: true, })) .catch((err: Error) => { sendResponse({ err: isNaN(Number(err.message)) ? 0 : Number(err.message), success: false, }); }); // means we want to return the response // asynchronously. return true; case Intent.MAL_QuickUpdate: mal .quickUpdate(message.animeId, message.episode) .then(() => sendResponse({ success: true, })) .catch((err: Error) => { sendResponse({ err: isNaN(Number(err.message)) ? 0 : Number(err.message), success: false, }); }); return true; case Intent.MAL_Userlist: mal .getUserList() .then(resp => sendResponse({ data: resp, success: true, })) .catch((err: Error) => { sendResponse({ err: isNaN(Number(err.message)) ? 0 : Number(err.message), success: false, }); }); return true; case Intent.MAL_Search: mal .search(message.animeName) .then(resp => sendResponse({ data: resp, success: true, })) .catch((err: Error) => { sendResponse({ err: isNaN(Number(err.message)) ? 0 : Number(err.message), success: false, }); }); return true; case Intent.MAL_VerifyCredentials: mal .verify(message.username, message.password) .then(resp => sendResponse({ success: true, })) .catch((err: Error) => { sendResponse({ err: isNaN(Number(err.message)) ? 0 : Number(err.message), success: false, }); }); return true; case Intent.MAL_RemoveCredentials: mal.removeCredentials(); sendResponse({ success: true, }); break; /**************************************************************************************************************/ case Intent.Install_Check: loadSettings("latestInstall").then(settings => { // if notification is already shown then we don't bother // sending it to the content script once again. if (settings.latestInstall && !settings.latestInstall.notificationShown) { let latestInstall = settings.latestInstall; sendResponse({ data: settings.latestInstall, success: true, }); latestInstall.notificationShown = true; chrome.storage.local.set({ latestInstall, }); } else { sendResponse({ success: false, }); } }); return true; default: console.info("Intent not valid"); break; } }); /* --- AntiAdblock --- */ /*const getUpdatedDetection = async() => { try { const resp = await fetch("https://github.com/lap00zza/9anime-Companion/raw/master/scripts/antiAdblock.json"); if (!resp.ok) { throw new Error(resp.status.toString()); } return await resp.json(); } catch (err) { throw new Error(err.message); } };*/ /* --- ~~~ --- */ chrome.runtime.onInstalled.addListener(details => { // let version = chrome.runtime.getManifest().version; let versionName = chrome.runtime.getManifest().version_name || ""; switch (details.reason) { case "install": chrome.storage.local.set({ latestInstall: { notificationShown: false, timestamp: new Date().toISOString(), type: "install", versionName, }, }); console.info("New install: Saving default settings to localStorage"); chrome.storage.local.set(Settings); break; case "update": // For version older than 1, we will delete all the previous settings. // Only if the major version is 1 or more we will preserve settings. // This is to make sure that the settings from the older version wont // conflict with the new settings. if (details.previousVersion && Number(details.previousVersion.split(".")[0]) >= 1) { // Preserve the previous settings and add the new default settings. let settingsKeys = Object.keys(Settings); let newSettings: IGenericObject = {}; chrome.storage.local.get(settingsKeys, previousSettings => { settingsKeys.forEach(key => { if (previousSettings[key] === undefined) { newSettings[key] = Settings[key]; } else { newSettings[key] = previousSettings[key]; } }); // TODO: add a way to preserve users filter list newSettings.adBlockFilters = Settings.adBlockFilters; }); chrome.storage.local.clear(() => { chrome.storage.local.set(newSettings); chrome.storage.local.set({ latestInstall: { notificationShown: false, timestamp: new Date().toISOString(), type: "update", versionName, }, }); }); console.info(`Updated to ${versionName}\nPreserving old settings and adding new ones`, newSettings); } else { console.info(`Updated to ${versionName}\nOlder version of 9anime Companion detected.` + ` Clearing old settings and adding new ones.`); // Clear the previous settings and add the new migrated settings. // This also helps clear out the settings that we no longer need. chrome.storage.local.clear(() => { chrome.storage.local.set(Settings); }); } break; default: break; } /* --- Load antiAdblockDetection snippet --- */ /*chrome.storage.local.set({ antiAdblock: { lastUpdated: "23-11-2017", snippet: "window.fai = {M: {},a: {}};Object.defineProperty(window, 'fai', {enumerable: true," + "configurable: false,writable: false});" + "window.fai = {M: {},a: {}};Object.defineProperty(window, 'fai', {enumerable: true," + "configurable: false,writable: false});" /!*+ "window.getComputedStyle = function (sel) {return {display: \"fuck\", visibility: \"you\"};};",*!/ }, }); getUpdatedDetection().then(r => { console.info("Successfully updated the antiAdblock..."); chrome.storage.local.set({ antiAdblock: r, }); });*/ /* --- ~~~ --- */ });
the_stack
import { gql } from "@adpt/core"; import express = require("express"); import { Express } from "express"; import { execute, GraphQLError, GraphQLResolveInfo, GraphQLSchema, printSchema } from "graphql"; import { makeExecutableSchema } from "graphql-tools"; import * as http from "http"; import * as https from "https"; import * as ld from "lodash"; import fetch from "node-fetch"; import should from "should"; import { Kubeconfig } from "../../src/k8s/common"; import k8sSwagger = require("../../src/k8s/kubernetes-1.18-swagger.json"); import swagger2gql, { ResolverFactory } from "../../src/swagger2gql"; import { Swagger2, Swagger2PathItem, Swagger2Schema } from "../../src/swagger2gql/swagger_types"; import { k8sSystemPodNameRegex } from "../k8s/testlib"; import { mkInstance } from "../run_minikube"; // tslint:disable-next-line:no-var-requires const swaggerClient = require("swagger-client"); function lineWithContext(txt: string, lineNo: number): string { const contextAmt = 10; const allLines = txt.split(/\r?\n/); const rawLines = allLines.slice(lineNo - contextAmt, lineNo + contextAmt); const lines = rawLines.map((l, i) => (lineNo - contextAmt + i + 1).toString() + ": " + l); return lines.join("\n"); } function reportGraphQLError<Ret>(txt: string, f: (txt: string) => Ret): Ret { try { return f(txt); } catch (e) { if (!(e instanceof GraphQLError)) throw e; const locations = e.locations; if (locations === undefined) throw e; let msg = e.toString() + "\n\n"; for (const loc of locations) { msg += lineWithContext(txt, loc.line) + "\n\n"; } throw new Error(msg); } } function makeSwagger( paths: { [path: string]: Swagger2PathItem }, definitions?: { [name: string]: Swagger2Schema }): Swagger2 { return { swagger: "2.0", info: { title: "Test spec", version: "1.0" }, paths, definitions }; } function makeSimpleGetSwagger(responseSchema: Swagger2Schema, apiPath: string = "/api", apiOp: string = "getApi") { return makeSwagger({ [apiPath]: { get: { operationId: apiOp, responses: { ["200"]: { description: "API response", schema: responseSchema } } } } }); } function makeMultiGetSwagger(paths: { path: string, op: string, responseSchema: Swagger2Schema }[]): Swagger2 { const ret: Swagger2 = { swagger: "2.0", info: { title: "Test spec", version: "1.0" }, paths: {} }; for (const p of paths) { const s = makeSimpleGetSwagger(p.responseSchema, p.path, p.op); ld.merge(ret, s); } return ret; } function swaggerResolverFactory(spec: Swagger2, host: string, agent?: https.Agent, headers?: { [index: string]: string }): ResolverFactory { if (spec.swagger !== "2.0") throw new Error(`Bad swagger version '${spec.swagger}'`); return { fieldResolvers: (_type, fieldName, isQuery) => { if (!isQuery) return; return async (_obj, args, _context, _info) => { const req = await swaggerClient.buildRequest({ spec, operationId: fieldName, parameters: args, requestContentType: "application/json", responseContentType: "application/json" }); const url = host + req.url; const resp = await fetch(url, { ...req, agent, headers }); if (resp.status !== 200) { throw new Error(`Error status ${resp.statusText}(${resp.status}): ${resp.body}`); } return resp.json(); }; } }; } describe("Swagger to GraphQL Tests (simple)", () => { it("Should convert with primitive response type", () => { const swagger = makeSimpleGetSwagger({ type: "string" }); const schema = swagger2gql(swagger); should(schema).not.Null(); should(schema).not.Undefined(); const schemaTxt = printSchema(schema); should(schemaTxt).match(/getApi: String/); }); it("Should convert with inline object response type", () => { const swagger = makeSimpleGetSwagger({ type: "object", required: ["bar"], properties: { foo: { type: "string" }, bar: { type: "integer" } } }); const schema = swagger2gql(swagger); should(schema).not.Null(); should(schema).not.Undefined(); const schemaTxt = printSchema(schema); should(schemaTxt).match(/getApi: getApi_Response/); should(schemaTxt).match(/foo: String/); should(schemaTxt).match(/bar: Int!/); }); it("Should convert with inline parameter types", () => { const swagger = makeSimpleGetSwagger({ type: "string" }); swagger.paths["/api"].get!.parameters = [ { name: "foo", in: "query", type: "integer", default: 3 }, { name: "bar", in: "query", type: "integer", required: true } ]; const schema = swagger2gql(swagger); should(schema).not.Null(); should(schema).not.Undefined(); const schemaTxt = printSchema(schema); should(schemaTxt).match(/getApi\(foo: Int = 3, bar: Int!\): String/); }); it("Should detect invalid swagger files", () => { should(() => swagger2gql({})).throwError(); //make sure cached status is valid should(() => swagger2gql({})).throwError(); }); it("Should convert with $ref parameter spec"); //Not supported yet it("Should convert with $ref response spec"); //Tested by k8s test cases below, add smaller tests in future here }); describe("Swagger to GraphQL Tests (with resolvers)", () => { it("Should resolve single field", async () => { const swagger = makeSimpleGetSwagger({ type: "integer" }); swagger.paths["/api"].get!.parameters = [ { name: "foo", in: "query", type: "integer", default: 3 } ]; const schema = swagger2gql(swagger, { fieldResolvers: (_type, fieldName) => { if (fieldName !== "getApi") throw new Error("fieldResolvers called for extraneous field"); return (_obj: unknown, args: { foo: number }, _context: unknown, _info: GraphQLResolveInfo) => { return args.foo + 1; }; } }); const result17 = await execute(schema, gql`query { getApi(foo: 17) }`); should(ld.cloneDeep(result17)).eql({ data: { getApi: 18 } }); const resultDefault = await execute(schema, gql`query { getApi }`); should(ld.cloneDeep(resultDefault)).eql({ data: { getApi: 4 } }); }); it("Should resolve multiple fields", async () => { const swagger = makeMultiGetSwagger([ { path: "/api/plus1", op: "plus1", responseSchema: { type: "integer" } }, { path: "/api/square", op: "square", responseSchema: { type: "integer" } } ]); swagger.paths["/api/plus1"].get!.parameters = [ { name: "addend", in: "query", type: "integer", default: 7 } ]; swagger.paths["/api/square"].get!.parameters = [ { name: "base", in: "query", type: "integer", default: 3 } ]; const schema = swagger2gql<unknown, unknown, { addend?: number; base?: number; }>(swagger, { fieldResolvers: (_type, fieldName) => { switch (fieldName) { case "plus1": return (_obj, args: { addend: number }, _context, _info) => { return args.addend + 1; }; case "square": return (_obj, args: { base: number }, _context, _info) => { return args.base * args.base; }; default: throw new Error("fieldResolvers called for extraneous field: " + fieldName); } } }); const resultPlus1 = await execute(schema, gql`query { plus1(addend: 17) }`); should(ld.cloneDeep(resultPlus1)).eql({ data: { plus1: 18 } }); const resultSquareDefault = await execute(schema, gql`query { square }`); should(ld.cloneDeep(resultSquareDefault)).eql({ data: { square: 9 } }); }); }); function authHeaders(user: { username?: string; password?: string }): {} | { Authorization: string } { if (!user.username || !user.password) return {}; const auth = Buffer.from(user.username + ":" + user.password).toString("base64"); return { Authorization: "Basic " + auth }; } function getK8sConnectInfo(kubeconfig: Kubeconfig) { function byName(name: string) { return (x: { name: string }) => x.name === name; } const contextName: string = kubeconfig["current-context"]; const context = kubeconfig.contexts.find(byName(contextName)); if (!context) throw new Error(`Could not find context ${contextName}`); const cluster = kubeconfig.clusters.find(byName(context.context.cluster)); const user = kubeconfig.users.find(byName(context.context.user)); if (!cluster) throw new Error(`Could not find cluster ${context.context.cluster}`); const caData = cluster.cluster["certificate-authority-data"]; const ca = caData ? Buffer.from(caData, "base64").toString() : undefined; const url = cluster.cluster.server; if (!user) throw new Error(`Could not find user ${context.context.user}`); const keyData = user.user["client-key-data"]; const certData = user.user["client-certificate-data"]; const key = keyData && Buffer.from(keyData, "base64").toString(); const cert = certData && Buffer.from(certData, "base64").toString(); const username = user.user.username; const password = user.user.password; return { ca, url, key, cert, username, password, }; } describe("Swagger to GraphQL Tests (with Kubernetes 1.8 spec)", () => { let schema: GraphQLSchema; before(async function () { this.timeout(30 * 1000 + mkInstance.setupTimeoutMs); const kubeconfig = await mkInstance.kubeconfig; const info = getK8sConnectInfo(kubeconfig as Kubeconfig); const agent = new https.Agent({ key: info.key, cert: info.cert, ca: info.ca, }); const host = info.url; const headers = authHeaders(info); schema = swagger2gql( k8sSwagger, swaggerResolverFactory(k8sSwagger as any as Swagger2, host, agent, headers)); }); it("Should convert and reparse schema", async () => { should(schema).not.Undefined(); should(schema).not.Null(); const schemaTxt = printSchema(schema); reportGraphQLError(schemaTxt, (s) => makeExecutableSchema({ typeDefs: s })); }); it("Should convert and fetch running pods", async () => { const result = await execute(schema, gql`query { listCoreV1NamespacedPod(namespace: "kube-system") { kind items { metadata { name } } } }`); should(result.errors).Undefined(); const data = result.data; if (data == null) throw should(data).be.ok(); const pods = data.listCoreV1NamespacedPod; if (pods === undefined) return should(pods).not.Undefined(); should(pods.kind).equal("PodList"); const items = pods.items as ({ metadata?: { name?: string } } | undefined)[]; if (items === undefined) return should(items).not.Undefined(); if (!ld.isArray(items)) return should(items).Array(); for (const item of items) { if (item === undefined) return should(item).not.Undefined(); const meta = item.metadata; if (meta === undefined) return should(meta).not.Undefined(); const name = meta.name; if (name === undefined) return should(name).not.Undefined(); return should(name).match(k8sSystemPodNameRegex); } should(items.length).equal(3); }); }); describe("Swagger to GraphQL remote query tests", () => { let mockServer: http.Server; let mockApp: Express; let mockHost: string; const mockSwagger: Swagger2 = { swagger: "2.0", info: { title: "Test spec", version: "1.0" }, paths: { "/api/plus1": { get: { operationId: "plus1", produces: ["application/json"], parameters: [{ name: "addend", in: "query", type: "integer" }], responses: { ["200"]: { description: "Addend + 1", schema: { type: "integer" } }, ["400"]: { description: "Bad Request", schema: { type: "string" } } } } }, "/api/square": { get: { operationId: "square", produces: ["application/json"], parameters: [{ name: "base", in: "query", type: "integer" }], responses: { ["200"]: { description: "Base squared", schema: { type: "integer" } }, ["400"]: { description: "Bad Request", schema: { type: "string" } } } } } } }; beforeEach(async () => { mockApp = express(); mockApp.get("/api/plus1", (req, res) => { const addendString = req.query.addend ? req.query.addend : "7"; const addend = Number(addendString); if (Number.isNaN(addend)) { res.status(400).json("Must have numeric addend"); } else { res.status(200).json(addend + 1); } res.end(); }); mockApp.get("/api/square", (req, res) => { const baseString = req.query.base ? req.query.base : "3"; const base = Number(baseString); if (Number.isNaN(base)) { res.status(400).send("Must have numeric addend"); } else { res.json(base * base); } res.end(); }); mockServer = http.createServer(mockApp); await new Promise((res, rej) => mockServer.listen((err: Error) => err ? rej(err) : res())); const addr = mockServer.address(); if (typeof addr === "string") throw new Error(`Expected an object`); mockHost = "http://localhost:" + addr.port.toString(); }); afterEach(async () => { await new Promise((res, rej) => mockServer.close((err: Error) => err ? rej(err) : res())); }); it("Server baseline (no graphql)", async () => { //This is just a baseline to make sure the server setup is working. //Doesn't test the library but is useful for diagnosing other test failures const req = await swaggerClient.buildRequest({ spec: mockSwagger, operationId: "plus1", parameters: { addend: 17 }, requestContentType: "application/json", responseContentType: "application/json" }); const url = mockHost + req.url; // tslint:disable-next-line:no-object-literal-type-assertion const resp = await fetch(url, req); should(resp.status).equal(200); should(await resp.json()).equal(18); }); it("Should connect to server and get data", async () => { const schema = swagger2gql(mockSwagger, swaggerResolverFactory(mockSwagger, mockHost)); const resultPlus1 = await execute(schema, gql`query { plus1(addend: 3) }`); should(ld.cloneDeep(resultPlus1)).eql({ data: { plus1: 4 } }); const resultSquare = await execute(schema, gql`query { square(base: 5) }`); should(ld.cloneDeep(resultSquare)).eql({ data: { square: 25 } }); }); });
the_stack
import {$test, LogLevel} from "typescript-logging"; import {CATEGORY_LOG_CONTROL, CATEGORY_PROVIDER_SERVICE} from "../main/impl/CategoryProviderService"; import {CategoryProvider} from "../main/api/CategoryProvider"; describe("Test CategoryControlProvider", () => { const message = new $test.TestControlMessage(); beforeEach(() => { /* * Clear any state, so we always start clean. */ CATEGORY_PROVIDER_SERVICE.clear(); message.clear(); }); test("Test fetching non-existing provider fails", () => { const control = CATEGORY_LOG_CONTROL(message.write); CategoryProvider.createProvider("test"); /* By number */ expect(() => control.getProvider(1)).toThrowError(new Error("Provider with index '1' does not exist (outside of range).")); expect(() => control.getProvider(-1)).toThrowError(new Error("Provider with index '-1' does not exist (outside of range).")); /* By name */ expect(() => control.getProvider("nope")).toThrowError(new Error("Provider with name 'nope' does not exist.")); }); test("Test the help is present for the control", () => { const control = CATEGORY_LOG_CONTROL(message.write); control.help(); expect(message.messages.join("\n")).toContain("You can use the following commands:"); }); test("Test fetching existing provider succeeds", () => { const control = CATEGORY_LOG_CONTROL(message.write); CategoryProvider.createProvider("test1"); CategoryProvider.createProvider("test2"); const controlProvider1 = control.getProvider("test1"); const controlProvider2 = control.getProvider("test2"); const controlProvider1ByIndex = control.getProvider(0); const controlProvider2ByIndex = control.getProvider(1); expect(controlProvider1.name).toEqual("test1"); expect(controlProvider2.name).toEqual("test2"); expect(controlProvider1ByIndex.name).toEqual("test1"); expect(controlProvider2ByIndex.name).toEqual("test2"); }); test("Test control provider shows current provider settings", () => { const control = CATEGORY_LOG_CONTROL(message.write); control.showSettings(); expect(message.messages).toEqual(["Available CategoryProviders:\n"]); CategoryProvider.createProvider("Awesome Provider"); CategoryProvider.createProvider("Even More Awesome Provider"); message.clear(); control.showSettings(); expect(message.messages).toEqual(["Available CategoryProviders:\n [0, Awesome Provider ]\n [1, Even More Awesome Provider]\n"]); /* Create 8 more, to get to 10 */ let expectedValue = "Available CategoryProviders:\n [ 0, Awesome Provider ]\n [ 1, Even More Awesome Provider]\n"; for (let i = 2; i < 10; i++) { const provider = CategoryProvider.createProvider("Another Awesome One: " + i); expectedValue += " [" + ((i < 10) ? " " + i : i) + ", " + provider.name + ((i < 10) ? " " : " ") + "]\n"; } message.clear(); control.showSettings(); expect(message.messages).toEqual([expectedValue]); }); test("Test control provider shows settings for a CategoryProvider", () => { const control = CATEGORY_LOG_CONTROL(message.write); const provider = CategoryProvider.createProvider("test"); const controlProvider = control.getProvider("test"); controlProvider.showSettings(); expect(message.messages).toEqual(["Available categories (CategoryProvider 'test'):\n"]); const root = provider.getCategory("root"); const child1 = root.getChildCategory("child 1"); child1.getChildCategory("child 1_1"); child1.getChildCategory("child 1_2"); const child2 = root.getChildCategory("child 2"); child2.getChildCategory("child 2_1"); message.clear(); controlProvider.showSettings(); const expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Error)]", " [2, child 1_1 (level=Error)]", " [3, child 1_2 (level=Error)]", " [4, child 2 (level=Error)]", " [5, child 2_1 (level=Error)]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); }); test("Test control provider can change level by index", () => { const control = CATEGORY_LOG_CONTROL(message.write); const provider = CategoryProvider.createProvider("test"); const controlProvider = control.getProvider("test"); controlProvider.showSettings(); const root = provider.getCategory("root"); const child1 = root.getChildCategory("child 1"); child1.getChildCategory("child 1_1"); child1.getChildCategory("child 1_2"); message.clear(); controlProvider.showSettings(); let expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Error)]", " [2, child 1_1 (level=Error)]", " [3, child 1_2 (level=Error)]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); message.clear(); /* Change by index 3 */ controlProvider.update("debug", 3); expect(message.messages).toEqual(["Successfully updated category 'child 1_2' by index '3' to log level 'debug' and recursively applied to children (if any)."]); message.clear(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Error)]", " [2, child 1_1 (level=Error)]", " [3, child 1_2 (level=Debug)]", ]; controlProvider.showSettings(); expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); message.clear(); /* Now update root to trace, should be applied recursively by default */ controlProvider.update("trace", 0); expect(message.messages).toEqual(["Successfully updated category 'root' by index '0' to log level 'trace' and recursively applied to children (if any)."]); message.clear(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Trace)]", " [1, child 1 (level=Trace)]", " [2, child 1_1 (level=Trace)]", " [3, child 1_2 (level=Trace)]", ]; controlProvider.showSettings(); expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); /* Some sanity checks, all should be trace - also new categories created from existing should take over trace */ expect(root.logLevel).toEqual(LogLevel.Trace); expect(child1.logLevel).toEqual(LogLevel.Trace); const child2 = root.getChildCategory("child 2"); expect(child2.logLevel).toEqual(LogLevel.Trace); /* Now only update child_1, non recursive */ message.clear(); controlProvider.update("info", 1, true); expect(message.messages).toEqual(["Successfully updated category 'child 1' by index '1' to log level 'info'."]); message.clear(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Trace)]", " [1, child 1 (level=Info )]", " [2, child 1_1 (level=Trace)]", " [3, child 1_2 (level=Trace)]", " [4, child 2 (level=Trace)]", ]; controlProvider.showSettings(); expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); }); it("Test control provider can reset to original log levels", () => { // noinspection DuplicatedCode const control = CATEGORY_LOG_CONTROL(message.write); const provider = CategoryProvider.createProvider("test"); const root = provider.getCategory("root"); const child1 = root.getChildCategory("child 1"); child1.getChildCategory("child 1_1"); const child2 = root.getChildCategory("child 2"); /* Change log levels */ provider.updateRuntimeSettingsCategory(child1, {level: LogLevel.Info}); provider.updateRuntimeSettingsCategory(child2, {level: LogLevel.Warn}); /* Create the control provider, it will store current levels to reset to later */ const controlProvider = control.getProvider("test"); controlProvider.showSettings(); let expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Info )]", " [2, child 1_1 (level=Info )]", " [3, child 2 (level=Warn )]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); controlProvider.update("debug", "root"); message.clear(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Debug)]", " [1, child 1 (level=Debug)]", " [2, child 1_1 (level=Debug)]", " [3, child 2 (level=Debug)]", ]; controlProvider.showSettings(); expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); /* Now reset it should go back to the initial */ controlProvider.reset(); message.clear(); controlProvider.showSettings(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Info )]", " [2, child 1_1 (level=Info )]", " [3, child 2 (level=Warn )]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); }); it("Test control provider can use save and restore", () => { // noinspection DuplicatedCode const control = CATEGORY_LOG_CONTROL(message.write); const provider = CategoryProvider.createProvider("test"); const root = provider.getCategory("root"); const child1 = root.getChildCategory("child 1"); child1.getChildCategory("child 1_1"); const child2 = root.getChildCategory("child 2"); /* Change log levels */ provider.updateRuntimeSettingsCategory(child1, {level: LogLevel.Info}); provider.updateRuntimeSettingsCategory(child2, {level: LogLevel.Warn}); /* Create the control provider, it will store current levels to reset to later */ const controlProvider = control.getProvider("test"); controlProvider.showSettings(); let expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Info )]", " [2, child 1_1 (level=Info )]", " [3, child 2 (level=Warn )]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); controlProvider.save(); controlProvider.reset(); message.clear(); provider.updateRuntimeSettingsCategory(child1, {level: LogLevel.Error}); provider.updateRuntimeSettingsCategory(child2, {level: LogLevel.Error}); controlProvider.showSettings(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Error)]", " [2, child 1_1 (level=Error)]", " [3, child 2 (level=Error)]", ]; expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); message.clear(); controlProvider.restore(true); expect(message.messages).toEqual(["Successfully restored state for CategoryControlProvider 'test'"]); message.clear(); expectedArr = [ "Available categories (CategoryProvider 'test'):", " [0, root (level=Error)]", " [1, child 1 (level=Info )]", " [2, child 1_1 (level=Info )]", " [3, child 2 (level=Warn )]", ]; controlProvider.showSettings(); expect(message.messages).toEqual([expectedArr.join("\n") + "\n"]); }); });
the_stack
import { UIDLUtils } from '@teleporthq/teleport-shared' import { Validator, Parser } from '@teleporthq/teleport-uidl-validator' import { GeneratorOptions, GeneratedFolder, Mapping, ProjectStrategy, ProjectStrategyComponentOptions, ComponentGenerator, ProjectStrategyPageOptions, ConfigGeneratorResult, ProjectPlugin, InMemoryFileRecord, TeleportError, GeneratorFactoryParams, HTMLComponentGenerator, } from '@teleporthq/teleport-types' import { injectFilesToPath, resolveLocalDependencies, createPageUIDLs, prepareComponentOutputOptions, generateExternalCSSImports, fileFileAndReplaceContent, bootstrapGenerator, generateLocalDependenciesPrefix, } from './utils' import { createManifestJSONFile, handlePackageJSON, createComponent, createPage, createRouterFile, createEntryFile, createComponentModule, createPageModule, } from './file-handlers' import { DEFAULT_TEMPLATE } from './constants' import ProjectAssemblyLine from './assembly-line' type UpdateGeneratorCallback = (generator: ComponentGenerator) => void export class ProjectGenerator { public componentGenerator: ComponentGenerator | HTMLComponentGenerator public pageGenerator: ComponentGenerator | HTMLComponentGenerator public routerGenerator: ComponentGenerator public styleSheetGenerator: ComponentGenerator private strategy: ProjectStrategy private validator: Validator private assemblyLine: ProjectAssemblyLine constructor(strategy: ProjectStrategy) { this.validator = new Validator() this.strategy = strategy this.assemblyLine = new ProjectAssemblyLine() } public getStrategy() { return this.strategy } public updateStrategy(strategy: Partial<ProjectStrategy>) { this.strategy = { ...this.strategy, ...strategy } } public updateGenerator(callback: UpdateGeneratorCallback) { this.updateComponentsGenerator(callback) this.updatePagesGenerator(callback) } public updateComponentsGenerator(callback: UpdateGeneratorCallback) { if (typeof callback === 'function') { callback(this.strategy.components.generator()) } } public updatePagesGenerator(callback: UpdateGeneratorCallback) { if (typeof callback === 'function') { callback(this.strategy.pages.generator()) } } public updateComponentsStrategy({ generator, path, options, }: { generator?: ComponentGenerator path?: string[] options?: ProjectStrategyComponentOptions }) { if (generator) { this.strategy.components.generator = () => generator } if (path) { this.strategy.components.path = path } if (options && Object.keys(options).length > 0) { this.strategy.components.options = { ...this.strategy.components.options, ...options } } } public updatePagesStrategy({ generator, path, options, }: { generator?: ComponentGenerator path?: string[] options?: ProjectStrategyPageOptions }) { if (generator) { this.strategy.pages.generator = () => generator } if (path) { this.strategy.pages.path = path } if (options && Object.keys(options).length > 0) { this.strategy.pages.options = { ...this.strategy.pages.options, ...options } } } public async generateProject( input: Record<string, unknown>, template: GeneratedFolder = DEFAULT_TEMPLATE, mapping: Mapping = {} ): Promise<GeneratedFolder> { let cleanedUIDL = input let collectedDependencies: Record<string, string> = {} let collectedDevDependencies: Record<string, string> = {} let inMemoryFilesMap = new Map<string, InMemoryFileRecord>() // Initialize output folder and other reusable structures const rootFolder = UIDLUtils.cloneObject(template || DEFAULT_TEMPLATE) const schemaValidationResult = this.validator.validateProjectSchema(input) const { valid, projectUIDL } = schemaValidationResult if (valid && projectUIDL) { cleanedUIDL = projectUIDL as unknown as Record<string, unknown> } else { throw new Error(schemaValidationResult.errorMsg) } const uidl = Parser.parseProjectJSON(cleanedUIDL) const contentValidationResult = this.validator.validateProjectContent(uidl) if (!contentValidationResult.valid) { throw new Error(contentValidationResult.errorMsg) } try { const runBeforeResult = await this.assemblyLine.runBefore({ uidl, template, files: inMemoryFilesMap, strategy: this.strategy, dependencies: collectedDependencies, devDependencies: collectedDevDependencies, rootFolder, }) collectedDependencies = { ...collectedDependencies, ...runBeforeResult.dependencies } collectedDevDependencies = { ...collectedDevDependencies, ...runBeforeResult.devDependencies } this.strategy = runBeforeResult.strategy inMemoryFilesMap = runBeforeResult.files if (this.strategy.components?.generator) { this.componentGenerator = bootstrapGenerator(this.strategy.components, this.strategy.style) } if (this.strategy.pages?.generator) { this.pageGenerator = bootstrapGenerator(this.strategy.pages, this.strategy.style) } if (this.strategy.projectStyleSheet?.generator) { this.styleSheetGenerator = bootstrapGenerator( this.strategy.projectStyleSheet, this.strategy.style ) } if (this.strategy.router?.generator) { this.routerGenerator = bootstrapGenerator(this.strategy.router, this.strategy.style) } } catch (e) { throw new TeleportError(`Error in Generating Project after runBefore - ${e}`) } const { components = {} } = uidl const { styleSetDefinitions = {}, designLanguage: { tokens = {} } = {} } = uidl.root // Based on the routing roles, separate pages into distict UIDLs with their own file names and paths const pageUIDLs = createPageUIDLs(uidl, this.strategy) if (Object.keys(components).length > 0) { // Set the filename and folder path for each component based on the strategy prepareComponentOutputOptions(components, this.strategy) // Set the local dependency paths based on the relative paths between files resolveLocalDependencies(pageUIDLs, components, this.strategy) } // If static prefix is not specified, compute it from the path, but if the string is empty it should work const assetsPrefix = typeof this.strategy.static.prefix === 'string' ? this.strategy.static.prefix : '/' + this.getAssetsPath().join('/') const options: GeneratorOptions = { assetsPrefix, projectRouteDefinition: uidl.root.stateDefinitions.route, mapping, skipValidation: true, designLanguage: uidl.root?.designLanguage, } // Handling project style sheet if ( this.strategy.projectStyleSheet?.generator && (Object.keys(styleSetDefinitions).length > 0 || Object.keys(tokens).length > 0) ) { const { files, dependencies } = await this.styleSheetGenerator.generateComponent(uidl.root, { isRootComponent: true, }) inMemoryFilesMap.set('projectStyleSheet', { path: this.strategy.projectStyleSheet.path, files, }) collectedDependencies = { ...collectedDependencies, ...dependencies } } // Handling pages for (const pageUIDL of pageUIDLs) { if (!this.strategy?.pages?.generator) { throw new TeleportError( `Pages Generator is missing from the strategy - ${JSON.stringify(this.strategy.pages)}` ) } let pageOptions = options if (this.strategy.projectStyleSheet) { pageOptions = { ...options, projectStyleSet: { styleSetDefinitions, fileName: this.strategy.projectStyleSheet.fileName, path: generateLocalDependenciesPrefix( this.strategy.pages.path, this.strategy.projectStyleSheet.path ), importFile: this.strategy.projectStyleSheet?.importFile || false, }, designLanguage: uidl.root?.designLanguage, } } if ((this.pageGenerator as HTMLComponentGenerator)?.addExternalComponents) { ;(this.pageGenerator as unknown as HTMLComponentGenerator).addExternalComponents({ externals: components, skipValidation: true, }) } const { files, dependencies } = await createPage(pageUIDL, this.pageGenerator, pageOptions) // Pages might be generated inside subfolders in the main pages folder const relativePath = UIDLUtils.getComponentFolderPath(pageUIDL) const path = this.strategy.pages.path.concat(relativePath) inMemoryFilesMap.set(pageUIDL.name, { path, files, }) collectedDependencies = { ...collectedDependencies, ...dependencies } if (this.strategy.pages?.module) { const pageModuleGenerator = bootstrapGenerator( this.strategy.pages.module, this.strategy.style ) const pageModule = await createPageModule(pageUIDL, pageModuleGenerator, options) inMemoryFilesMap.set(`${pageUIDL.name}Module`, { path, files: pageModule.files, }) collectedDependencies = { ...collectedDependencies, ...pageModule.dependencies } } } // Handling module generation for components if (this.strategy?.components?.module) { const componentModuleGenerator = bootstrapGenerator( this.strategy.components.module, this.strategy.style ) const componentsModule = await createComponentModule( uidl, this.strategy, componentModuleGenerator ) inMemoryFilesMap.set(componentsModule.files[0].name, { path: this.strategy.components.path, files: componentsModule.files, }) collectedDependencies = { ...collectedDependencies, ...componentsModule.dependencies } } // Handling components for (const componentName of Object.keys(components)) { if (!this.strategy?.components?.generator) { throw new TeleportError( `Component Generator is missing from the strategy - ${JSON.stringify( this.strategy.components )}` ) } let componentOptions = options if (this.strategy.projectStyleSheet) { componentOptions = { ...options, projectStyleSet: { styleSetDefinitions, fileName: this.strategy.projectStyleSheet.fileName, path: generateLocalDependenciesPrefix( this.strategy.components.path, this.strategy.projectStyleSheet.path ), importFile: this.strategy.projectStyleSheet?.importFile || false, }, designLanguage: uidl.root?.designLanguage, } } if ((this.componentGenerator as HTMLComponentGenerator)?.addExternalComponents) { ;(this.componentGenerator as unknown as HTMLComponentGenerator).addExternalComponents({ externals: components, skipValidation: true, }) } const componentUIDL = components[componentName] const { files, dependencies } = await createComponent( componentUIDL, this.componentGenerator, componentOptions ) // Components might be generated inside subfolders in the main components folder const relativePath = UIDLUtils.getComponentFolderPath(componentUIDL) const path = this.strategy.components.path.concat(relativePath) inMemoryFilesMap.set(componentName, { path, files, }) collectedDependencies = { ...collectedDependencies, ...dependencies } } // Handling framework specific changes to the project const { framework } = this.strategy // Can be used for replacing a couple of strings if (framework?.replace) { const shouldAddChanges = Boolean( framework.replace?.isGlobalStylesDependent && (Object.keys(styleSetDefinitions).length > 0 || Object.keys(uidl?.root?.designLanguage?.tokens || {}).length > 0) ) if (shouldAddChanges) { const { fileName, fileType } = framework.replace const result = framework.replace.replaceFile( template, collectedDependencies, fileName, fileType ) collectedDependencies = result.dependencies inMemoryFilesMap.set(fileName, { path: this.strategy.framework.replace.path, files: [result.file], }) } } // If we want to generate a completly new file if (framework?.config) { const { fileName, fileType, configContentGenerator, generator, plugins: frameworkConfigPlugins, } = framework.config if (configContentGenerator && generator) { const result: ConfigGeneratorResult = configContentGenerator({ fileName, fileType, globalStyles: { path: generateLocalDependenciesPrefix( framework.config.path, this.strategy.projectStyleSheet.path ), sheetName: this.strategy.projectStyleSheet ? this.strategy.projectStyleSheet.fileName : '', isGlobalStylesDependent: framework.config?.isGlobalStylesDependent ?? Boolean( Object.keys(styleSetDefinitions).length > 0 || Object.keys(uidl.root?.designLanguage?.tokens || {}).length > 0 ), }, dependencies: collectedDependencies, }) collectedDependencies = result.dependencies if (Object.keys(result?.chunks).length > 0) { const configGenerator: (params: GeneratorFactoryParams) => ComponentGenerator = framework.config.generator const files = configGenerator({ plugins: frameworkConfigPlugins }).linkCodeChunks( result.chunks, framework.config.fileName ) inMemoryFilesMap.set(fileName, { path: this.strategy.framework.config.path, files, }) } } } // Global settings are transformed into the root html file and the manifest file for PWA support if (uidl.globals.manifest) { const manifestFile = createManifestJSONFile(uidl, assetsPrefix) inMemoryFilesMap.set(manifestFile.name, { path: this.strategy.static.path, files: [manifestFile], }) } // TODO: Projects which don't need a router file will miss collecting // dependencies which are specified on them // Create the routing component in case the project generator has a strategy for that if (this.strategy.router) { const { routerFile, dependencies } = await createRouterFile( uidl.root, this.strategy, this.routerGenerator ) inMemoryFilesMap.set('router', { path: this.strategy.router.path, files: [routerFile], }) collectedDependencies = { ...collectedDependencies, ...dependencies } } // Create the entry file of the project (ex: index.html, _document.js) if (this.strategy.entry) { const entryFile = await createEntryFile(uidl, this.strategy, { assetsPrefix, }) inMemoryFilesMap.set('entry', { path: this.strategy.entry.path, files: entryFile, }) } // If the framework needs all the external css dependencies to be placed in some other file if (framework?.externalStyles && this.strategy.pages.options?.useFileNameForNavigation) { const { fileName } = framework.externalStyles const folder = inMemoryFilesMap.get(fileName) if (!folder) { throw new Error(`Canno't find file - ${fileName} from the list of files generated`) } const [resultFile] = await generateExternalCSSImports(uidl.root) const files = fileFileAndReplaceContent(folder.files, fileName, resultFile.content) inMemoryFilesMap.set(fileName, { path: folder.path, files, }) } try { const runAfterResult = await this.assemblyLine.runAfter({ uidl, template, files: inMemoryFilesMap, strategy: this.strategy, dependencies: collectedDependencies, devDependencies: collectedDevDependencies, rootFolder, }) collectedDependencies = { ...collectedDependencies, ...runAfterResult.dependencies } collectedDevDependencies = { ...collectedDevDependencies, ...runAfterResult.devDependencies } inMemoryFilesMap = runAfterResult.files } catch (e) { throw new TeleportError(`Error in generating project after runAfter - ${e}`) } inMemoryFilesMap.forEach((stage) => { injectFilesToPath(rootFolder, stage.path, stage.files) }) // Inject all the collected dependencies in the package.json file handlePackageJSON(rootFolder, uidl, collectedDependencies, collectedDevDependencies) return rootFolder } public addMapping(mapping: Mapping) { this.strategy.components.mappings = [...this.strategy.components?.mappings, mapping] this.strategy.pages.mappings = [...this.strategy.pages?.mappings, mapping] if (this.strategy.router) { /* TODO: Add mapping later if we decide to reference a generator object instead of a generator function for routing */ } } public addPlugin(plugin: ProjectPlugin) { this.assemblyLine.addPlugin(plugin) } public cleanPlugins() { this.assemblyLine.cleanPlugins() } public getAssetsPath() { return this.strategy.static.path } } export const createProjectGenerator = (strategy: ProjectStrategy): ProjectGenerator => { return new ProjectGenerator(strategy) } export default createProjectGenerator
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const memberOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'member', ], }, }, options: [ { name: 'Delete', value: 'delete', description: 'Delete a member', }, { name: 'Get', value: 'get', description: 'Get a member', }, { name: 'Get All', value: 'getAll', description: 'Get all members in a workspace', }, { name: 'Lookup', value: 'lookup', description: 'Lookup a member by identity', }, { name: 'Update', value: 'update', description: 'Update a member', }, { name: 'Upsert', value: 'upsert', description: 'Create/Update a member', }, ], default: 'get', description: 'The operation to perform.', }, ]; export const memberFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* member:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'delete', ], }, }, description: 'The workspace', }, { displayName: 'Member ID', name: 'memberId', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'delete', ], }, }, description: 'Member ID', }, /* -------------------------------------------------------------------------- */ /* member:get */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'get', ], }, }, description: 'The workspace', }, { displayName: 'Member ID', name: 'memberId', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'get', ], }, }, description: 'Member ID', }, { displayName: 'Resolve Identities', name: 'resolveIdentities', type: 'boolean', displayOptions: { show: { operation: [ 'get', ], resource: [ 'member', ], }, }, default: false, description: 'By default, the response just includes the reference of the identity. When set to true the identities will be resolved automatically.', }, /* -------------------------------------------------------------------------- */ /* member:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'getAll', ], }, }, description: 'The workspace', }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'member', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'member', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 500, }, default: 100, description: 'How many results to return.', }, { displayName: 'Resolve Identities', name: 'resolveIdentities', type: 'boolean', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'member', ], }, }, default: false, description: 'By default, the response just includes the reference of the identity. When set to true the identities will be resolved automatically.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { resource: [ 'member', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Sort By', name: 'sort', type: 'string', default: '', description: 'Name of the field the response will be sorted by.', }, { displayName: 'Sort Direction', name: 'direction', type: 'options', options: [ { name: 'ASC', value: 'ASC', }, { name: 'DESC', value: 'DESC', }, ], default: '', }, ], }, /* -------------------------------------------------------------------------- */ /* member:lookup */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], }, }, description: 'The workspace', }, { displayName: 'Source', name: 'source', type: 'options', options: [ { name: 'Discourse', value: 'discourse', }, { name: 'Email', value: 'email', }, { name: 'GitHub', value: 'github', }, { name: 'Twitter', value: 'twitter', }, ], default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], }, }, description: `Set to github, twitter, email, discourse or the source of any identities you've manually created.`, }, { displayName: 'Search By', name: 'searchBy', type: 'options', options: [ { name: 'Username', value: 'username', }, { name: 'ID', value: 'id', }, ], default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], source: [ 'discourse', 'github', 'twitter', ], }, }, }, { displayName: 'ID', name: 'id', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], searchBy: [ 'id', ], source: [ 'discourse', 'github', 'twitter', ], }, }, description: `The username at the source.`, }, { displayName: 'Username', name: 'username', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], searchBy: [ 'username', ], source: [ 'discourse', 'github', 'twitter', ], }, }, description: `The username at the source.`, }, { displayName: 'Email', name: 'email', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], source: [ 'email', ], }, }, description: `The email address.`, }, { displayName: 'Host', name: 'host', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'lookup', ], source: [ 'discourse', ], }, }, }, /* -------------------------------------------------------------------------- */ /* member:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'update', ], }, }, }, { displayName: 'Member ID', name: 'memberId', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'member', ], operation: [ 'update', ], }, }, default: {}, options: [ { displayName: 'Bio', name: 'bio', type: 'string', default: '', }, { displayName: 'Birthday', name: 'birthday', type: 'dateTime', default: '', }, { displayName: 'Company', name: 'company', type: 'string', default: '', }, { displayName: 'Location', name: 'location', type: 'string', default: '', }, { displayName: 'Name', name: 'name', type: 'string', default: '', }, { displayName: 'Pronouns', name: 'pronouns', type: 'string', default: '', }, { displayName: 'Shipping Address', name: 'shippingAddress', type: 'string', default: '', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', }, { displayName: 'Tags to Add', name: 'tagsToAdd', type: 'string', default: '', description: 'Adds tags to member; comma-separated string or array', }, { displayName: 'Tag List', name: 'tagList', type: 'string', default: '', description: 'Replaces all tags for the member; comma-separated string or array', }, { displayName: 'T-Shirt', name: 'tShirt', type: 'string', default: '', }, { displayName: 'Teammate', name: 'teammate', type: 'boolean', default: false, }, { displayName: 'URL', name: 'url', type: 'string', default: '', }, ], }, /* -------------------------------------------------------------------------- */ /* member:upsert */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', required: true, displayOptions: { show: { resource: [ 'member', ], operation: [ 'upsert', ], }, }, }, { displayName: 'Identity', name: 'identityUi', type: 'fixedCollection', description: 'The identity is used to find the member. If no member exists, a new member will be created and linked to the provided identity.', typeOptions: { multipleValues: false, }, placeholder: 'Add Identity', default: {}, displayOptions: { show: { resource: [ 'member', ], operation: [ 'upsert', ], }, }, options: [ { displayName: 'Identity', name: 'identityValue', values: [ { displayName: 'Source', name: 'source', type: 'options', options: [ { name: 'Discourse', value: 'discourse', }, { name: 'Email', value: 'email', }, { name: 'GitHub', value: 'github', }, { name: 'Twitter', value: 'twitter', }, ], default: '', description: `Set to github, twitter, email, discourse or the source of any identities you've manually created.`, }, { displayName: 'Search By', name: 'searchBy', type: 'options', options: [ { name: 'Username', value: 'username', }, { name: 'ID', value: 'id', }, ], default: '', required: true, displayOptions: { show: { source: [ 'discourse', 'github', 'twitter', ], }, }, }, { displayName: 'ID', name: 'id', type: 'string', default: '', required: true, displayOptions: { show: { searchBy: [ 'id', ], source: [ 'discourse', 'github', 'twitter', ], }, }, description: `The username at the source.`, }, { displayName: 'Username', name: 'username', type: 'string', default: '', required: true, displayOptions: { show: { searchBy: [ 'username', ], source: [ 'discourse', 'github', 'twitter', ], }, }, description: `The username at the source.`, }, { displayName: 'Email', name: 'email', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'email', ], }, }, }, { displayName: 'Host', name: 'host', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'discourse', ], }, }, }, ], }, ], }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'member', ], operation: [ 'upsert', ], }, }, default: {}, options: [ { displayName: 'Bio', name: 'bio', type: 'string', default: '', }, { displayName: 'Birthday', name: 'birthday', type: 'dateTime', default: '', }, { displayName: 'Company', name: 'company', type: 'string', default: '', }, { displayName: 'Location', name: 'location', type: 'string', default: '', }, { displayName: 'Name', name: 'name', type: 'string', default: '', }, { displayName: 'Pronouns', name: 'pronouns', type: 'string', default: '', }, { displayName: 'Shipping Address', name: 'shippingAddress', type: 'string', default: '', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', }, { displayName: 'Tags to Add', name: 'tagsToAdd', type: 'string', default: '', description: 'Adds tags to member; comma-separated string or array.', }, { displayName: 'Tag List', name: 'tagList', type: 'string', default: '', description: 'Replaces all tags for the member; comma-separated string or array.', }, { displayName: 'T-Shirt', name: 'tShirt', type: 'string', default: '', }, { displayName: 'Teammate', name: 'teammate', type: 'boolean', default: false, }, { displayName: 'URL', name: 'url', type: 'string', default: '', }, ], }, ];
the_stack
import { values, reduce, isString, keyBy, isPlainObject, isEmpty, concat, mapValues } from 'lodash'; import { GraphQLFieldConfig, parse, FieldDefinitionNode, NamedTypeNode, TypeDefinitionNode, GraphQLNamedType, GraphQLUnionTypeConfig, GraphQLEnumTypeConfig, GraphQLObjectTypeConfig, GraphQLInputObjectTypeConfig, GraphQLScalarTypeConfig, GraphQLInterfaceTypeConfig, getDescription, ObjectTypeDefinitionNode, InputObjectTypeDefinitionNode, ScalarTypeDefinitionNode, InterfaceTypeDefinitionNode, EnumTypeDefinitionNode, UnionTypeDefinitionNode, GraphQLSchema, GraphQLObjectType, GraphQLScalarType, GraphQLInterfaceType, GraphQLEnumType, GraphQLUnionType, GraphQLInputObjectType, printSchema, print, Kind, TypeNode, NonNullTypeNode, ListTypeNode, NameNode } from 'graphql'; import { ObjectType, NamedType, EnumType } from './dataModel'; import Field from './dataModel/field'; import { compose } from 'lodash/fp'; import { IResolverObject } from 'graphql-tools'; // tslint:disable-next-line:no-var-requires const { ASTDefinitionBuilder } = require('graphql/utilities/buildASTSchema'); const keyByNameNode = ( list: Array<{name: NameNode}>, valFn: (item: {name: NameNode}) => any, ) => { return reduce(list, (result, field) => { result[field.name.value] = valFn(field); return result; }, {}); }; const buildTypeNodeFromField = (field: Field): TypeNode => { const wrapped: Array<(node: TypeNode) => TypeNode> = []; if (field.isNonNull()) { wrapped.push(node => { // tslint:disable-next-line:no-object-literal-type-assertion return { kind: Kind.NON_NULL_TYPE, type: node, } as NonNullTypeNode; }); } if (field.isList()) { wrapped.push(node => { // tslint:disable-next-line:no-object-literal-type-assertion return { kind: Kind.LIST_TYPE, type: node, } as ListTypeNode; }); if (field.isNonNullItem()) { wrapped.push(node => { // tslint:disable-next-line:no-object-literal-type-assertion return { kind: Kind.NON_NULL_TYPE, type: node, } as NonNullTypeNode; }); } } const typeNode: NamedTypeNode = { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: field.getTypename(), }, }; return compose(wrapped)(typeNode); }; export default class RootNode { private defBuilder: any; private resolvers: IResolverObject = {}; // todo: figure out GraphQLFieldConfig general type private queryMap: Record<string, () => GraphQLFieldConfig<any, any>> = {}; private mutationMap: Record<string, () => GraphQLFieldConfig<any, any>> = {}; private objectTypeMap: Record<string, GraphQLObjectTypeConfig<any, any>> = {}; private inputMap: Record<string, GraphQLInputObjectTypeConfig> = {}; private scalars: GraphQLScalarType[] = []; private interfaceMap: Record<string, GraphQLInterfaceTypeConfig<any, any>> = {}; private enumMap: Record<string, GraphQLEnumTypeConfig> = {}; private unionMap: Record<string, GraphQLUnionTypeConfig<any, any>> = {}; constructor() { this.defBuilder = new ASTDefinitionBuilder({}, {}, typeRef => { throw new Error(`Type "${typeRef.name.value}" not found in document.`); }); } /** * Resolver related */ public addResolver(resolverObject: IResolverObject) { this.resolvers = { ...this.resolvers, ...resolverObject, }; } public getResolvers() { return this.resolvers; } /** * GraphQL API related */ // query could be queryName(args): type, or a GraphQLFieldConfig public addQuery(query: string | {name: string, field: () => GraphQLFieldConfig<any, any>}) { const {name, field} = isPlainObject(query) ? query as {name: string, field: () => GraphQLFieldConfig<any, any>} : this.buildField(query as string); this.queryMap[name] = field; } // mutation could be mutationName(args): type, or a GraphQLFieldConfig public addMutation(mutation: string | {name: string, field: () => GraphQLFieldConfig<any, any>}) { const {name, field} = isPlainObject(mutation) ? mutation as {name: string, field: () => GraphQLFieldConfig<any, any>} : this.buildField(mutation as string); this.mutationMap[name] = field; } public addObjectType(type: string | ObjectType) { const {name, def} = this.buildObjectType(type); this.objectTypeMap[name] = this.buildObjectTypeConfig(def); } public addInput(input: string | InputObjectTypeDefinitionNode) { const {name, def} = this.buildType<InputObjectTypeDefinitionNode>(input); this.inputMap[name] = this.buildInputTypeConfig(def); } public addScalar(scalar: GraphQLScalarType) { this.scalars.push(scalar); } public addInterface(interfaceDef: string) { const {name, def} = this.buildType<InterfaceTypeDefinitionNode>(interfaceDef); this.interfaceMap[name] = this.buildInterfaceTypeConfig(def); } public addEnum(enumDef: string | EnumType) { const {name, def} = this.buildEnumType(enumDef); this.enumMap[name] = this.buildEnumTypeConfig(def); } public addUnion(unionDef: string | UnionTypeDefinitionNode) { const {name, def} = this.buildType<UnionTypeDefinitionNode>(unionDef); this.unionMap[name] = this.buildUnionTypeConfig(def); } public buildSchema() { const operationTypes = { query: isEmpty(this.queryMap) ? null : new GraphQLObjectType({ name: 'Query', fields: () => mapValues(this.queryMap, field => field()), }), mutation: isEmpty(this.mutationMap) ? null : new GraphQLObjectType({ name: 'Mutation', fields: () => mapValues(this.mutationMap, field => field()), }), }; const scalarDefs = this.scalars; const interfaceDefs = values<GraphQLInterfaceTypeConfig<any, any>>(this.interfaceMap) .map(typeConfig => new GraphQLInterfaceType(typeConfig)); const enumDefs = values<GraphQLEnumTypeConfig>(this.enumMap) .map(typeConfig => new GraphQLEnumType(typeConfig)); const unionDefs = values<GraphQLUnionTypeConfig<any, any>>(this.unionMap) .map(typeConfig => new GraphQLUnionType(typeConfig)); const objectTypeDefs = values<GraphQLObjectTypeConfig<any, any>>(this.objectTypeMap) .map(typeConfig => new GraphQLObjectType(typeConfig)); const inputTypeDefs = values<GraphQLInputObjectTypeConfig>(this.inputMap) .map(typeConfig => new GraphQLInputObjectType(typeConfig)); const typeDefs: GraphQLNamedType[] = concat<GraphQLNamedType>(scalarDefs, interfaceDefs, enumDefs, unionDefs, objectTypeDefs, inputTypeDefs); typeDefs.forEach(type => { this.defBuilder._cache[type.name] = type; }); return new GraphQLSchema({ query: operationTypes.query, mutation: operationTypes.mutation, types: typeDefs, }); } public print() { const schema = this.buildSchema(); return printSchema(schema); } private buildField(field: string): {name: string, field: () => GraphQLFieldConfig<any, any>} { // todo: find a better way to parse FieldDefinitionNode const fieldDef: FieldDefinitionNode = (parse(`type name {${field}}`).definitions[0] as any).fields[0]; return { name: fieldDef.name.value, field: () => this.defBuilder.buildField(fieldDef), }; } private buildObjectTypeConfig(typeDef: ObjectTypeDefinitionNode): GraphQLObjectTypeConfig<any, any> { const { fields, interfaces } = typeDef; return { name: typeDef.name.value, description: getDescription(typeDef, {}), fields: fields ? () => keyByNameNode(fields, field => this.defBuilder.buildInputField(field)) : {}, // Note: While this could make early assertions to get the correctly // typed values, that would throw immediately while type system // validation with validateSchema() will produce more actionable results. interfaces: interfaces ? () => interfaces.map(ref => this.defBuilder.buildType(ref)) : [], astNode: typeDef, }; } private buildInputTypeConfig(def: InputObjectTypeDefinitionNode): GraphQLInputObjectTypeConfig { return { name: def.name.value, description: getDescription(def, {}), fields: () => def.fields ? keyByNameNode(def.fields, field => this.defBuilder.buildInputField(field)) : {}, astNode: def, }; } private buildInterfaceTypeConfig(def: InterfaceTypeDefinitionNode): GraphQLInterfaceTypeConfig<any, any> { const fieldNodes = def.fields; const fields = fieldNodes && fieldNodes.length > 0 ? () => keyByNameNode(fieldNodes, field => this.defBuilder.buildField(field)) : {}; return { name: def.name.value, description: getDescription(def, {}), fields, astNode: def, }; } private buildEnumTypeConfig(def: EnumTypeDefinitionNode): GraphQLEnumTypeConfig { const valueNodes = def.values || []; return { name: def.name.value, description: getDescription(def, {}), values: keyByNameNode(valueNodes, value => this.defBuilder.buildEnumValue(value)), astNode: def, }; } private buildUnionTypeConfig(def: UnionTypeDefinitionNode): GraphQLUnionTypeConfig<any, any> { const types: NamedTypeNode[] = def.types; return { name: def.name.value, description: getDescription(def, {}), // Note: While this could make assertions to get the correctly typed // values below, that would throw immediately while type system // validation with validateSchema() will produce more actionable results. types: types ? () => types.map(ref => (this.defBuilder.buildType(ref) as any)) : [], astNode: def, }; } private buildType<TypeDefType = TypeDefinitionNode>(typeDef: string | TypeDefType): {name: string, def: TypeDefType} { const typeDefNode = isString(typeDef) ? parse(typeDef as string).definitions[0] as any : typeDef; const name = typeDefNode.name.value; this.defBuilder._typeDefinitionsMap[name] = typeDefNode; return {name, def: typeDefNode}; } private buildObjectType(typeDef: string | ObjectType): {name: string, def: ObjectTypeDefinitionNode} { const typeDefNode: ObjectTypeDefinitionNode = isString(typeDef) ? parse(typeDef as string).definitions[0] as ObjectTypeDefinitionNode : { kind: Kind.OBJECT_TYPE_DEFINITION, name: { kind: Kind.NAME, value: typeDef.getTypename(), }, fields: reduce(typeDef.getFields(), (arr, field, key) => { arr.push({ kind: Kind.FIELD_DEFINITION, name: { kind: Kind.NAME, value: key, }, type: buildTypeNodeFromField(field), }); return arr; }, []), }; const name = typeDefNode.name.value; this.defBuilder._typeDefinitionsMap[name] = typeDefNode; return {name, def: typeDefNode}; } private buildEnumType(typeDef: string | EnumType): {name: string, def: EnumTypeDefinitionNode} { const typeDefNode: EnumTypeDefinitionNode = isString(typeDef) ? parse(typeDef as string).definitions[0] as EnumTypeDefinitionNode : { kind: Kind.ENUM_TYPE_DEFINITION, name: { kind: Kind.NAME, value: typeDef.getTypename(), }, values: typeDef.getValues().map(value => { return { kind: Kind.ENUM_VALUE_DEFINITION, name: { kind: Kind.NAME, value, }, }; }), }; const name = typeDefNode.name.value; this.defBuilder._typeDefinitionsMap[name] = typeDefNode; return {name, def: typeDefNode}; } }
the_stack
import { OrbitControl } from "@oasis-engine/controls"; import * as dat from "dat.gui"; import { AmbientLight, AnimationClip, Animator, AssetType, BackgroundMode, BoundingBox, Camera, Color, DirectLight, Entity, GLTFResource, Logger, Material, MeshRenderer, PBRBaseMaterial, PBRMaterial, PBRSpecularMaterial, PrimitiveMesh, Renderer, Scene, SkinnedMeshRenderer, SkyBoxMaterial, Texture2D, UnlitMaterial, Vector3, WebGLEngine } from "oasis-engine"; Logger.enable(); const envList = { sunset: "https://gw.alipayobjects.com/os/bmw-prod/34986a5b-fa16-40f1-83c8-1885efe855d2.bin", pisa: "https://gw.alipayobjects.com/os/bmw-prod/258a783d-0673-4b47-907a-da17b882feee.bin", foot: "https://gw.alipayobjects.com/os/bmw-prod/f369110c-0e33-47eb-8296-756e9c80f254.bin" }; class Oasis { static guiToColor(gui: number[], color: Color) { color.setValue(gui[0] / 255, gui[1] / 255, gui[2] / 255, color.a); } static colorToGui(color: Color = new Color(1, 1, 1)): number[] { const v = []; v[0] = color.r * 255; v[1] = color.g * 255; v[2] = color.b * 255; return v; } textures: Record<string, Texture2D> = {}; env: Record<string, AmbientLight> = {}; engine: WebGLEngine = new WebGLEngine("canvas"); scene: Scene = this.engine.sceneManager.activeScene; skyMaterial: SkyBoxMaterial = new SkyBoxMaterial(this.engine); // Entity rootEntity: Entity = this.scene.createRootEntity("root"); cameraEntity: Entity = this.rootEntity.createChild("camera"); gltfRootEntity: Entity = this.rootEntity.createChild("gltf"); lightEntity1: Entity = this.rootEntity.createChild("direct_light1"); lightEntity2: Entity = this.rootEntity.createChild("direct_light2"); // Component camera: Camera = this.cameraEntity.addComponent(Camera); controler: OrbitControl = this.cameraEntity.addComponent(OrbitControl); light1: DirectLight = this.lightEntity1.addComponent(DirectLight); light2: DirectLight = this.lightEntity2.addComponent(DirectLight); // Debug gui = new dat.GUI(); materialFolder = null; animationFolder = null; state = { // Scene background: false, // Lights env: "sunset", envIntensity: 1, addLights: true, lightColor: Oasis.colorToGui(new Color(1, 1, 1)), lightIntensity: 0.8, // GLTF Model List defaultGLTF: "fox", gltfList: { "2CylinderEngine": "https://gw.alipayobjects.com/os/bmw-prod/48a1e8b3-06b4-4269-807d-79274e58283a.glb", alphaBlendModeTest: "https://gw.alipayobjects.com/os/bmw-prod/d099b30b-59a3-42e4-99eb-b158afa8e65d.glb", animatedCube: "https://gw.alipayobjects.com/os/bmw-prod/8cc524dd-2481-438d-8374-3c933adea3b6.gltf", antiqueCamera: "https://gw.alipayobjects.com/os/bmw-prod/93196534-bab3-4559-ae9f-bcb3e36a6419.glb", avocado: "https://gw.alipayobjects.com/os/bmw-prod/0f978c4d-1cd6-4cec-9a4c-b58c8186e063.glb", avocado_draco: "https://gw.alipayobjects.com/os/bmw-prod/b3b73614-cf06-4f41-940d-c1bc04cf6410.gltf", avocado_specular: "https://gw.alipayobjects.com/os/bmw-prod/3cf50452-0015-461e-a172-7ea1f8135e53.gltf", avocado_quantized: "https://gw.alipayobjects.com/os/bmw-prod/6aff5409-8e82-4e77-a6ac-55b6adfd0cf5.gltf", barramundiFish: "https://gw.alipayobjects.com/os/bmw-prod/79d7935c-404b-4d8d-9ad3-5f8c273f0e4a.glb", boomBox: "https://gw.alipayobjects.com/os/bmw-prod/2e98b1c0-18e8-45d0-b54e-dcad6ef05e22.glb", boomBoxWithAxes: "https://gw.alipayobjects.com/os/bmw-prod/96e1b8b2-9be6-4b64-98ea-8c008c6dc422.gltf", boxVertexColors: "https://gw.alipayobjects.com/os/bmw-prod/6cff6fcb-5191-465e-9a38-dee42a07cc65.glb", brianStem: "https://gw.alipayobjects.com/os/bmw-prod/e3b37dd9-9407-4b5c-91b3-c5880d081329.glb", buggy: "https://gw.alipayobjects.com/os/bmw-prod/d6916a14-b004-42d5-86dd-d8520b719288.glb", cesiumMan: "https://gw.alipayobjects.com/os/bmw-prod/3a7d9597-7354-4bef-b314-b84509bef9b6.glb", cesiumMilkTruck: "https://gw.alipayobjects.com/os/bmw-prod/7701125a-7d0d-4281-a7d8-7f0dfc8d0792.glb", corset: "https://gw.alipayobjects.com/os/bmw-prod/3deaa5a4-5b2a-4a0d-8512-a8c4377a08ff.glb", DamagedHelmet: "https://gw.alipayobjects.com/os/bmw-prod/a1da72a4-023e-4bb1-9629-0f4b0f6b6fc4.glb", Duck: "https://gw.alipayobjects.com/os/bmw-prod/6cb8f543-285c-491a-8cfd-57a1160dc9ab.glb", environmentTest: "https://gw.alipayobjects.com/os/bmw-prod/7c7b887c-05d6-43dd-b354-216e738e81ed.gltf", flightHelmet: "https://gw.alipayobjects.com/os/bmw-prod/d6dbf161-48e2-4e6d-bbca-c481ed9f1a2d.gltf", fox: "https://gw.alipayobjects.com/os/bmw-prod/f40ef8dd-4c94-41d4-8fac-c1d2301b6e47.glb", animationInterpolationTest: "https://gw.alipayobjects.com/os/bmw-prod/4f410ef2-20b4-494d-85f1-a806c5070bfb.glb", lantern: "https://gw.alipayobjects.com/os/bmw-prod/9557420a-c622-4e9c-bb46-f7af8b19d7de.glb", materialsVariantsShoe: "https://gw.alipayobjects.com/os/bmw-prod/b1a414bb-61ea-4667-94d2-ef6cf179ac0d.glb", metalRoughSpheres: "https://gw.alipayobjects.com/os/bmw-prod/67b39ede-1c82-4321-8457-0ad83ca9413a.glb", normalTangentTest: "https://gw.alipayobjects.com/os/bmw-prod/4bb1a66c-55e3-4898-97d7-a9cc0f239686.glb", normalTangentMirrorTest: "https://gw.alipayobjects.com/os/bmw-prod/8335f555-2061-47f5-9252-366c6ebf882a.glb", orientationTest: "https://gw.alipayobjects.com/os/bmw-prod/16cdf390-ac42-411c-9d2b-8e112dfd723b.glb", sparseTest: "https://gw.alipayobjects.com/os/bmw-prod/f00de659-53ea-49d1-8f2c-d0a412542b80.gltf", specGlossVsMetalRough: "https://gw.alipayobjects.com/os/bmw-prod/4643bd7b-f988-4144-8245-4a390023d92d.glb", sponza: "https://gw.alipayobjects.com/os/bmw-prod/ca50859b-d736-4a3e-9fc3-241b0bd2afef.gltf", suzanne: "https://gw.alipayobjects.com/os/bmw-prod/3869e495-2e04-4e80-9d22-13b37116379a.gltf", sheenChair: "https://gw.alipayobjects.com/os/bmw-prod/34847225-bc1b-4bef-9cb9-6b9711ca2f8c.glb", sheenCloth: "https://gw.alipayobjects.com/os/bmw-prod/4529d2e8-22a8-47af-9b38-8eaff835f6bf.gltf", textureCoordinateTest: "https://gw.alipayobjects.com/os/bmw-prod/5fd23201-51dd-4eea-92d3-c4a72ecc1f2b.glb", textureEncodingTest: "https://gw.alipayobjects.com/os/bmw-prod/b8795e57-3c2c-4412-b4f0-7ffa796e4917.glb", textureSettingTest: "https://gw.alipayobjects.com/os/bmw-prod/a4b26d58-bd49-4051-8f05-0fe8b532e716.glb", textureTransformMultiTest: "https://gw.alipayobjects.com/os/bmw-prod/8fa18786-5188-4c14-94d7-77bf6b8483f9.glb", textureTransform: "https://gw.alipayobjects.com/os/bmw-prod/6c59d5d0-2e2e-4933-a737-006d431977fd.gltf", toyCar: "https://gw.alipayobjects.com/os/bmw-prod/8138b7d7-45aa-494a-8aea-0c67598b96d2.glb", transmissionTest: "https://gw.alipayobjects.com/os/bmw-prod/1dd51fe8-bdd3-42e4-99be-53de5dc106b8.glb", unlitTest: "https://gw.alipayobjects.com/os/bmw-prod/06a855be-ac8c-4705-b5d7-659b8b391189.glb", vc: "https://gw.alipayobjects.com/os/bmw-prod/b71c4212-25fb-41bb-af88-d79ce6d3cc58.glb", vertexColorTest: "https://gw.alipayobjects.com/os/bmw-prod/8fc70cc6-66d8-43c8-b460-f7d2aaa9edcf.glb", waterBottle: "https://gw.alipayobjects.com/os/bmw-prod/0f403530-96f5-455a-8a39-b31ac68b6ed5.glb" } }; _materials: Material[] = []; // temporary _boundingBox: BoundingBox = new BoundingBox(); _center: Vector3 = new Vector3(); _extent: Vector3 = new Vector3(); constructor() { this.initResources().then(() => { this.initScene(); this.addGLTFList(); this.addSceneGUI(); }); } initResources() { const names = Object.keys(envList); return new Promise((resolve) => { this.engine.resourceManager .load( names.map((name) => { return { type: AssetType.Env, url: envList[name] }; }) ) .then((envs: AmbientLight[]) => { envs.forEach((env: AmbientLight, index) => { const name = names[index]; this.env[name] = env; if (name === this.state.env) { this.scene.ambientLight = env; this.skyMaterial.textureCubeMap = env.specularTexture; this.skyMaterial.textureDecodeRGBM = true; } }); resolve(true); }); }); } initScene() { this.engine.canvas.resizeByClientSize(); this.controler.minDistance = 0; // debug sync if (this.state.background) { this.scene.background.mode = BackgroundMode.Sky; } if (!this.state.addLights) { this.light1.enabled = this.light2.enabled = false; } this.light1.intensity = this.light2.intensity = this.state.lightIntensity; this.lightEntity1.transform.setRotation(30, 0, 0); this.lightEntity2.transform.setRotation(-30, 180, 0); this.scene.ambientLight.specularIntensity = this.state.envIntensity; this.scene.background.sky.material = this.skyMaterial; this.scene.background.sky.mesh = PrimitiveMesh.createCuboid(this.engine, 1, 1, 1); this.engine.run(); } addGLTFList() { this.loadGLTF(this.state.gltfList[this.state.defaultGLTF]); this.gui .add(this.state, "defaultGLTF", Object.keys(this.state.gltfList)) .name("GLTF List") .onChange((v) => { this.loadGLTF(this.state.gltfList[v]); }); } addSceneGUI() { const { gui } = this; // Display controls. const dispFolder = gui.addFolder("Scene"); dispFolder.add(this.state, "background").onChange((v: boolean) => { if (v) { this.scene.background.mode = BackgroundMode.Sky; } else { this.scene.background.mode = BackgroundMode.SolidColor; } }); // Lighting controls. const lightFolder = gui.addFolder("Lighting"); lightFolder .add(this.state, "env", [...Object.keys(this.env)]) .name("IBL") .onChange((v) => { this.scene.ambientLight = this.env[v]; this.skyMaterial.textureCubeMap = this.env[v].specularTexture; }); lightFolder .add(this.state, "addLights") .onChange((v) => { this.light1.enabled = this.light2.enabled = v; }) .name("直接光"); lightFolder.addColor(this.state, "lightColor").onChange((v) => { Oasis.guiToColor(v, this.light1.color); Oasis.guiToColor(v, this.light2.color); }); lightFolder .add(this.state, "lightIntensity", 0, 2) .onChange((v) => { this.light1.intensity = this.light2.intensity = v; }) .name("直接光强度"); } setCenter(renderers: Renderer[]) { const boundingBox = this._boundingBox; const center = this._center; const extent = this._extent; boundingBox.min.setValue(0, 0, 0); boundingBox.max.setValue(0, 0, 0); renderers.forEach((renderer) => { BoundingBox.merge(renderer.bounds, boundingBox, boundingBox); }); boundingBox.getExtent(extent); const size = extent.length(); boundingBox.getCenter(center); this.controler.target.setValue(center.x, center.y, center.z); this.cameraEntity.transform.setPosition(center.x, center.y, size * 3); this.camera.farClipPlane = size * 12; if (this.camera.nearClipPlane > size) { this.camera.nearClipPlane = size / 10; } else { this.camera.nearClipPlane = 0.1; } this.controler.maxDistance = size * 10; } loadGLTF(url: string) { this.destroyGLTF(); const isGLB = /.glb$/.test(url); this.engine.resourceManager .load<GLTFResource>({ type: AssetType.Prefab, url: `${url}#${Math.random()}.${isGLB ? "glb" : "gltf"}` // @todo: resourceManager cache bug }) .then((asset) => { const { defaultSceneRoot, materials, animations } = asset; console.log(asset); this.gltfRootEntity = defaultSceneRoot; this.rootEntity.addChild(defaultSceneRoot); const meshRenderers = []; const skinnedMeshRenderers = []; defaultSceneRoot.getComponentsIncludeChildren(MeshRenderer, meshRenderers); defaultSceneRoot.getComponentsIncludeChildren(SkinnedMeshRenderer, skinnedMeshRenderers); this.setCenter(meshRenderers.concat(skinnedMeshRenderers)); this.loadMaterialGUI(materials); this.loadAnimationGUI(animations); }) .catch((e) => { console.error(e); }); } destroyGLTF() { this.gltfRootEntity.destroy(); } loadMaterialGUI(materials?: Material[]) { const { gui } = this; if (this.materialFolder) { gui.removeFolder(this.materialFolder); this.materialFolder = null; } if (!materials) { materials = this._materials; } this._materials = materials; if (!materials.length) return; const folder = (this.materialFolder = gui.addFolder("Material")); const folderName = {}; materials.forEach((material) => { if (!(material instanceof PBRBaseMaterial) && !(material instanceof UnlitMaterial)) return; if (!material.name) { material.name = "default"; } const state = { opacity: material.baseColor.a, baseColor: Oasis.colorToGui(material.baseColor), emissiveColor: Oasis.colorToGui((material as PBRBaseMaterial).emissiveColor), specularColor: Oasis.colorToGui((material as PBRSpecularMaterial).specularColor), baseTexture: material.baseTexture ? "origin" : "", roughnessMetallicTexture: (material as PBRMaterial).roughnessMetallicTexture ? "origin" : "", normalTexture: (material as PBRBaseMaterial).normalTexture ? "origin" : "", emissiveTexture: (material as PBRBaseMaterial).emissiveTexture ? "origin" : "", occlusionTexture: (material as PBRBaseMaterial).occlusionTexture ? "origin" : "", specularGlossinessTexture: (material as PBRSpecularMaterial).specularGlossinessTexture ? "origin" : "" }; const originTexture = { baseTexture: material.baseTexture, roughnessMetallicTexture: (material as PBRMaterial).roughnessMetallicTexture, normalTexture: (material as PBRBaseMaterial).normalTexture, emissiveTexture: (material as PBRBaseMaterial).emissiveTexture, occlusionTexture: (material as PBRBaseMaterial).occlusionTexture, specularGlossinessTexture: (material as PBRSpecularMaterial).specularGlossinessTexture }; const f = folder.addFolder( folderName[material.name] ? `${material.name}_${folderName[material.name] + 1}` : material.name ); folderName[material.name] = folderName[material.name] == null ? 1 : folderName[material.name] + 1; // metallic if (material instanceof PBRMaterial) { const mode1 = f.addFolder("金属模式"); mode1.add(material, "metallic", 0, 1).step(0.01); mode1.add(material, "roughness", 0, 1).step(0.01); mode1 .add(state, "roughnessMetallicTexture", ["None", "origin", ...Object.keys(this.textures)]) .onChange((v) => { material.roughnessMetallicTexture = v === "None" ? null : this.textures[v] || originTexture.roughnessMetallicTexture; }); mode1.open(); } // specular else if (material instanceof PBRSpecularMaterial) { const mode2 = f.addFolder("高光模式"); mode2.add(material, "glossiness", 0, 1).step(0.01); mode2.addColor(state, "specularColor").onChange((v) => { Oasis.guiToColor(v, material.specularColor); }); mode2 .add(state, "specularGlossinessTexture", ["None", "origin", ...Object.keys(this.textures)]) .onChange((v) => { material.specularGlossinessTexture = v === "None" ? null : this.textures[v] || originTexture.specularGlossinessTexture; }); mode2.open(); } else if (material instanceof UnlitMaterial) { f.add(state, "baseTexture", ["None", "origin", ...Object.keys(this.textures)]).onChange((v) => { material.baseTexture = v === "None" ? null : this.textures[v] || originTexture.baseTexture; }); f.addColor(state, "baseColor").onChange((v) => { Oasis.guiToColor(v, material.baseColor); }); } // common if (!(material instanceof UnlitMaterial)) { const common = f.addFolder("通用"); common .add(state, "opacity", 0, 1) .step(0.01) .onChange((v) => { material.baseColor.a = v; }); common.add(material, "isTransparent"); common.add(material, "alphaCutoff", 0, 1).step(0.01); common.addColor(state, "baseColor").onChange((v) => { Oasis.guiToColor(v, material.baseColor); }); common.addColor(state, "emissiveColor").onChange((v) => { Oasis.guiToColor(v, material.emissiveColor); }); common.add(state, "baseTexture", ["None", "origin", ...Object.keys(this.textures)]).onChange((v) => { material.baseTexture = v === "None" ? null : this.textures[v] || originTexture.baseTexture; }); common.add(state, "normalTexture", ["None", "origin", ...Object.keys(this.textures)]).onChange((v) => { material.normalTexture = v === "None" ? null : this.textures[v] || originTexture.normalTexture; }); common.add(state, "emissiveTexture", ["None", "origin", ...Object.keys(this.textures)]).onChange((v) => { material.emissiveTexture = v === "None" ? null : this.textures[v] || originTexture.emissiveTexture; }); common.add(state, "occlusionTexture", ["None", "origin", ...Object.keys(this.textures)]).onChange((v) => { material.occlusionTexture = v === "None" ? null : this.textures[v] || originTexture.occlusionTexture; }); common.open(); } }); } loadAnimationGUI(animations: AnimationClip[]) { if (this.animationFolder) { this.gui.removeFolder(this.animationFolder); this.animationFolder = null; } if (animations?.length) { this.animationFolder = this.gui.addFolder("Animation"); this.animationFolder.open(); const animator = this.gltfRootEntity.getComponent(Animator); animator.play(animations[0].name); const state = { animation: animations[0].name }; this.animationFolder .add(state, "animation", ["None", ...animations.map((animation) => animation.name)]) .onChange((name) => { if (name === "None") { animator.speed = 0; } else { animator.speed = 1; animator.play(name); } }); } } } new Oasis();
the_stack
import { common, TriggerType, UInt160, VMState } from '@neo-one/client-common'; import { createChild, nodeLogger } from '@neo-one/logger'; import { Action, ActionSource, ActionType, ApplicationExecuted, assertByteStringStackItem, Batch, Block, BlockAccountPolicyChange, ContractParameter, ExecFeeFactorPolicyChange, FeePerBytePolicyChange, GasPerBlockPolicyChange, LogAction, MinimumDeploymentFeePolicyChange, Notification, NotificationAction, RegisterCandidatePolicyChange, RegisterPricePolicyChange, RoleDesignationPolicyChange, SnapshotHandler, StackItem, stackItemToJSON, StoragePricePolicyChange, Transaction, TransactionData, UnblockAccountPolicyChange, UnregisterCandidatePolicyChange, VM, VMProtocolSettingsIn, Vote, } from '@neo-one/node-core'; import { utils as commonUtils } from '@neo-one/utils'; import { BN } from 'bn.js'; import { PersistNativeContractsError, PostPersistError } from './errors'; import { getExecutionResult } from './getExecutionResult'; import { utils } from './utils'; const logger = createChild(nodeLogger, { service: 'persisting-blockchain' }); interface PersistingBlockchainOptions { readonly vm: VM; readonly onPersistNativeContractScript: Buffer; readonly postPersistNativeContractScript: Buffer; readonly protocolSettings: VMProtocolSettingsIn; } export class PersistingBlockchain { private readonly vm: VM; private readonly onPersistNativeContractScript: Buffer; private readonly postPersistNativeContractScript: Buffer; private readonly protocolSettings: VMProtocolSettingsIn; public constructor({ vm, onPersistNativeContractScript, postPersistNativeContractScript, protocolSettings, }: PersistingBlockchainOptions) { this.vm = vm; this.onPersistNativeContractScript = onPersistNativeContractScript; this.postPersistNativeContractScript = postPersistNativeContractScript; this.protocolSettings = protocolSettings; } public persistBlock( block: Block, lastGlobalActionIndexIn: BN, lastGlobalTransactionIndex: BN, ): { // tslint:disable-next-line: readonly-array readonly changeBatch: Batch[]; readonly transactionData: readonly TransactionData[]; readonly applicationsExecuted: readonly ApplicationExecuted[]; readonly actions: readonly Action[]; readonly lastGlobalActionIndex: BN; readonly blockActionsCount: number; } { return this.vm.withSnapshots(({ main, clone }) => { const onPersistExecuted = this.vm.withApplicationEngine<ApplicationExecuted>( { trigger: TriggerType.OnPersist, snapshot: 'main', gas: new BN(0), persistingBlock: block, settings: this.protocolSettings, }, (engine) => { engine.loadScript({ script: this.onPersistNativeContractScript }); const result = engine.execute(); if (result !== VMState.HALT) { throw new PersistNativeContractsError(engine.faultException); } return utils.getApplicationExecuted(engine); }, ); main.clone(); const { transactionData, executedTransactions, actions: txActions, lastGlobalActionIndex: lastGlobalActionIndexTxs, } = this.persistTransactions( block, main, clone, lastGlobalActionIndexIn.add(utils.ONE), lastGlobalTransactionIndex, ); const postPersistExecuted = this.postPersist(block); const { actions: onPersistActions, lastGlobalActionIndex: lastGlobalActionIndexOnPersist } = this.getActionsFromAppExecuted(onPersistExecuted, lastGlobalActionIndexTxs, ActionSource.Block); const { actions: postPersistActions, lastGlobalActionIndex } = this.getActionsFromAppExecuted( postPersistExecuted, lastGlobalActionIndexOnPersist, ActionSource.Block, ); return { changeBatch: main.getChangeSet(), transactionData, blockActionsCount: onPersistActions.length + postPersistActions.length, actions: txActions.concat(onPersistActions, postPersistActions), lastGlobalActionIndex: lastGlobalActionIndex.sub(utils.ONE), applicationsExecuted: executedTransactions.concat(onPersistExecuted).concat(postPersistExecuted), }; }); } private getActionsFromAppExecuted( appExecuted: ApplicationExecuted, lastGlobalActionIndexIn: BN, source: ActionSource, ): { readonly actions: readonly Action[]; readonly lastGlobalActionIndex: BN } { let lastGlobalActionIndex = lastGlobalActionIndexIn; const actions: Action[] = []; appExecuted.notifications.forEach((notification) => { actions.push( new NotificationAction({ source, index: lastGlobalActionIndex, scriptHash: notification.scriptHash, eventName: notification.eventName, args: notification.state.map((n) => n.toContractParameter()), }), ); lastGlobalActionIndex = lastGlobalActionIndex.add(utils.ONE); }); appExecuted.logs.forEach((log) => { actions.push( new LogAction({ source, index: lastGlobalActionIndex, scriptHash: log.callingScriptHash, message: log.message, position: log.position, }), ); lastGlobalActionIndex = lastGlobalActionIndex.add(utils.ONE); }); return { actions, lastGlobalActionIndex }; } private getContractManagementInfo( appExecuted: ApplicationExecuted, block: Block, ): { readonly deletedContractHashes: readonly UInt160[]; readonly deployedContractHashes: readonly UInt160[]; readonly updatedContractHashes: readonly UInt160[]; } { const contractManagementNotifications = appExecuted.notifications.filter((n) => n.scriptHash.equals(common.nativeHashes.ContractManagement), ); const getUInt160 = (item: StackItem) => common.bufferToUInt160(assertByteStringStackItem(item).getBuffer()); const mapFilterUInt160s = (notifications: readonly Notification[], eventName: string) => notifications .filter((n) => n.eventName === eventName) .filter((n) => { try { getUInt160(n.state[0]); } catch (error) { logger.error({ name: 'contract_management_info_parse_error', index: block.index, event: eventName, // tslint:disable-next-line: no-unnecessary-callback-wrapper state: n.state.map((item) => stackItemToJSON(item)), error, }); return false; } return true; }) .map((n) => { const hash = getUInt160(n.state[0]); logger.debug({ title: 'new_contract_management_action', index: block.index, event: eventName, hash: common.uInt160ToString(hash), }); return hash; }); const updatedContractHashes = mapFilterUInt160s(contractManagementNotifications, 'Update'); const deletedContractHashes = mapFilterUInt160s(contractManagementNotifications, 'Destroy'); const deployedContractHashes = mapFilterUInt160s(contractManagementNotifications, 'Deploy'); return { deletedContractHashes, deployedContractHashes, updatedContractHashes }; } private getVotes(actions: readonly Action[]) { return actions .filter((a): a is NotificationAction => a.type === ActionType.Notification) .filter((n) => n.eventName === 'Vote' && common.uInt160Equal(n.scriptHash, common.nativeHashes.NEO)) .map((n) => { const vote = new Vote({ account: common.bufferToUInt160(n.args[0].asBuffer()), voteTo: n.args[1].isNull ? common.ECPOINT_INFINITY : common.bufferToECPoint(n.args[1].asBuffer()), balance: n.args[2].asInteger(), index: n.index, }); logger.debug({ title: 'new_vote', ...vote.serializeJSON() }); return vote; }); } private getPolicyChanges(actions: readonly Action[]) { const getECPoint = (item: ContractParameter) => common.bufferToECPoint(item.asBuffer()); const getUInt160 = (item: ContractParameter) => common.bufferToUInt160(item.asBuffer()); const getBN = (item: ContractParameter) => item.asInteger(); return actions .filter((n): n is NotificationAction => n.type === ActionType.Notification) .filter( (n) => common.uInt160Equal(n.scriptHash, common.nativeHashes.NEO) || common.uInt160Equal(n.scriptHash, common.nativeHashes.RoleManagement) || common.uInt160Equal(n.scriptHash, common.nativeHashes.Policy) || common.uInt160Equal(n.scriptHash, common.nativeHashes.ContractManagement), ) .map((n) => { const val = n.args[0]; const index = n.index; let result; switch (n.eventName) { case 'GasPerBlock': result = new GasPerBlockPolicyChange({ value: getBN(val), index }); break; case 'RegisterPrice': result = new RegisterPricePolicyChange({ value: getBN(val), index }); break; case 'UnregisterCandidate': result = new UnregisterCandidatePolicyChange({ value: getECPoint(val), index }); break; case 'RegisterCandidate': result = new RegisterCandidatePolicyChange({ value: getECPoint(val), index }); break; case 'Designation': result = new RoleDesignationPolicyChange({ value: getBN(val).toNumber(), index }); break; case 'FeePerByte': result = new FeePerBytePolicyChange({ value: getBN(val), index }); break; case 'ExecFeeFactor': result = new ExecFeeFactorPolicyChange({ value: getBN(val).toNumber(), index }); break; case 'StoragePrice': result = new StoragePricePolicyChange({ value: getBN(val).toNumber(), index }); break; case 'BlockAccount': result = new BlockAccountPolicyChange({ value: getUInt160(val), index }); break; case 'UnblockAccount': result = new UnblockAccountPolicyChange({ value: getUInt160(val), index }); break; case 'MinimumDeploymentFee': result = new MinimumDeploymentFeePolicyChange({ value: getBN(val), index }); break; default: result = undefined; } if (result !== undefined) { logger.debug({ title: 'new_policy_change', ...result.serializeJSON() }); } return result; }) .filter(commonUtils.notNull); } private persistTransactions( block: Block, main: SnapshotHandler, clone: Omit<SnapshotHandler, 'clone'>, lastGlobalActionIndexIn: BN, lastGlobalTransactionIndex: BN, ): { readonly transactionData: readonly TransactionData[]; readonly executedTransactions: readonly ApplicationExecuted[]; readonly lastGlobalActionIndex: BN; readonly actions: readonly Action[]; } { return block.transactions.reduce<{ readonly transactionData: readonly TransactionData[]; readonly executedTransactions: readonly ApplicationExecuted[]; readonly actions: readonly Action[]; readonly lastGlobalActionIndex: BN; }>( (acc, transaction, transactionIndex) => { const appExecuted = this.persistTransaction(transaction, main, clone, block); const { actions: newActions, lastGlobalActionIndex } = this.getActionsFromAppExecuted( appExecuted, acc.lastGlobalActionIndex, ActionSource.Transaction, ); const executionResult = getExecutionResult(appExecuted); const { deletedContractHashes, deployedContractHashes, updatedContractHashes } = this.getContractManagementInfo( appExecuted, block, ); const votes = this.getVotes(newActions); const policyChanges = this.getPolicyChanges(newActions); const txData = new TransactionData({ votes, policyChanges, hash: transaction.hash, blockHash: block.hash, deletedContractHashes, deployedContractHashes, updatedContractHashes, executionResult, actionIndexStart: acc.lastGlobalActionIndex, actionIndexStop: lastGlobalActionIndex, transactionIndex, blockIndex: block.index, globalIndex: lastGlobalTransactionIndex.add(new BN(transactionIndex + 1)), }); return { transactionData: acc.transactionData.concat(txData), executedTransactions: acc.executedTransactions.concat(appExecuted), actions: acc.actions.concat(newActions), lastGlobalActionIndex, }; }, { transactionData: [], executedTransactions: [], actions: [], lastGlobalActionIndex: lastGlobalActionIndexIn }, ); } private persistTransaction( transaction: Transaction, main: SnapshotHandler, clone: Omit<SnapshotHandler, 'clone'>, block: Block, ): ApplicationExecuted { return this.vm.withApplicationEngine( { trigger: TriggerType.Application, container: transaction, snapshot: 'clone', gas: transaction.systemFee, persistingBlock: block, settings: this.protocolSettings, }, (engine) => { engine.loadScript({ script: transaction.script }); const state = engine.execute(); if (state === VMState.HALT) { clone.commit(); } else { main.clone(); } return utils.getApplicationExecuted(engine, transaction); }, ); } private postPersist(block: Block): ApplicationExecuted { return this.vm.withApplicationEngine( { trigger: TriggerType.PostPersist, container: undefined, gas: new BN(0), snapshot: 'main', persistingBlock: block, settings: this.protocolSettings, }, (engine) => { engine.loadScript({ script: this.postPersistNativeContractScript }); const result = engine.execute(); if (result !== VMState.HALT) { throw new PostPersistError(engine.faultException); } return utils.getApplicationExecuted(engine); }, ); } }
the_stack
import { DisposableStore, Emitter, Event, IDisposable } from '@velcro/common'; type AnyFunc = (...args: any[]) => any; export type DefineEvent<TEventName extends string, TData = never> = { eventName: TEventName; data: TData; }; type AnyEvent = DefineEvent<string> | DefineEvent<string, unknown>; type EventWithData<TEvent extends AnyEvent> = TEvent extends AnyEvent ? [TEvent['data']] extends [never] ? never : TEvent : never; type EventWithoutData<TEvent extends AnyEvent> = Exclude<TEvent, EventWithData<TEvent>>; export type DefineState<TStateName extends string, TData = never> = TStateName extends string ? [TData] extends [never] ? { stateName: TStateName; } : { stateName: TStateName; data: TData; } : never; type AnyState = DefineState<string> | DefineState<string, unknown>; export type OnEnterHandlerContext< TState extends AnyState, TEvent extends AnyEvent, TStateName extends TState['stateName'] = TState['stateName'] > = { event: TEvent; registerDisposable(disposable: IDisposable): void; sendEvent: SendEventFunction<TEvent>; state: Extract<TState, { stateName: TStateName }>; transitionTo: TransitionToFunction<TState, TEvent>; }; export type OnEnterHandlerFunction< TState extends AnyState, TEvent extends AnyEvent, TStateName extends TState['stateName'] = TState['stateName'] > = (ctx: OnEnterHandlerContext<TState, TEvent, TStateName>) => void; /** * Conditional, mapped type that takes valid states (`TStates`), valid events (`TEvents`) * and actions and results in only the *names* of those actions that can be used as enter * handlers for the state `TStateName`. */ type OnEnterHandlerAction< TState extends AnyState, TEvent extends AnyEvent, TStateName extends TState['stateName'], TActions extends { [name: string]: AnyFunc } > = { [TActionName in keyof TActions]: TActions[TActionName] extends OnEnterHandlerFunction< TState, TEvent, TStateName > ? TActionName : never; }[keyof TActions]; export type OnEventHandlerContext< TState extends AnyState, TEvent extends AnyEvent, TEventName extends TEvent['eventName'] = TEvent['eventName'], TStateName extends TState['stateName'] = TState['stateName'] > = { event: Extract<TEvent, { eventName: TEventName }>; registerDisposable(disposable: IDisposable): void; sendEvent: SendEventFunction<TEvent>; state: Extract<TState, { stateName: TStateName }>; transitionTo: TransitionToFunction<TState, TEvent>; }; export type OnEventHandlerFunction< TState extends AnyState, TEvent extends AnyEvent, TEventName extends TEvent['eventName'] = TEvent['eventName'], TStateName extends TState['stateName'] = TState['stateName'] > = (ctx: OnEventHandlerContext<TState, TEvent, TEventName, TStateName>) => void; export type OnExitHandlerContext< TState extends AnyState, TEvent extends AnyEvent, TStateName extends TState['stateName'] = TState['stateName'] > = { event: TEvent; state: Extract<TState, { stateName: TStateName }> }; export type OnExitHandlerFunction< TState extends AnyState, TEvent extends AnyEvent, TStateName extends TState['stateName'] = TState['stateName'] > = (ctx: OnExitHandlerContext<TState, TEvent, TStateName>) => void; type ChartDefinition< TState extends AnyState, TEvent extends AnyEvent, TActions extends { [name: string]: AnyFunc } = Record<never, AnyFunc> > = { onEnter?: OnEnterHandlerFunction<TState, TEvent>; onEvent?: { [TEventName in TEvent['eventName']]?: OnEventHandlerFunction<TState, TEvent, TEventName>; }; onExit?: OnExitHandlerFunction<TState, TEvent>; states: { [TStateName in TState['stateName']]: { onEnter?: | OnEnterHandlerFunction<TState, TEvent, TStateName> | OnEnterHandlerAction<TState, TEvent, TStateName, TActions>; onEvent?: { [TEventName in TEvent['eventName']]?: OnEventHandlerFunction< TState, TEvent, TEventName, TStateName >; }; onExit?: OnExitHandlerFunction<TState, TEvent, TStateName>; }; }; }; interface SendEventFunction<TEvent extends AnyEvent> { <TSentEvent extends EventWithoutData<TEvent>>(eventName: TSentEvent['eventName']): void; <TSentEvent extends EventWithData<TEvent>>( eventName: TSentEvent['eventName'], data: TSentEvent['data'] ): void; } interface TransitionToFunction<TState extends AnyState, TEvent extends AnyEvent> { <TTargetState extends TState, TTriggeringEvent extends TEvent>( state: TTargetState, event: TTriggeringEvent ): void; } export class FSM< TState extends AnyState, TEvent extends AnyEvent, TActions extends { [name: string]: AnyFunc } = Record<never, AnyFunc> > { private readonly onEventEmitter = new Emitter<Readonly<TEvent>>(); private readonly onStateChangeEmitter = new Emitter<Readonly<TState>>(); private readonly actions: TActions; private readonly states: ChartDefinition<TState, TEvent, TActions>; private handlingEvents = false; private isDisposed = false; private mutableState: TState; private pendingExternalEvents: TEvent[] = []; private pendingInternalEvents: TEvent[] = []; private readonly stateDisposer = new DisposableStore(); constructor( states: ChartDefinition<TState, TEvent, TActions>, initialState: TState, actions?: TActions ) { this.states = states; this.mutableState = initialState; this.actions = actions || ({} as TActions); } get onEvent(): Event<Readonly<TEvent>> { return this.onEventEmitter.event; } get onStateChange(): Event<Readonly<TState>> { return this.onStateChangeEmitter.event; } get state(): Readonly<TState> { return this.mutableState; } dispose() { this.stateDisposer.dispose(); this.isDisposed = true; } sendEvent<TSentEvent extends EventWithoutData<TEvent>>(event: TSentEvent['eventName']): void; sendEvent<TSentEvent extends EventWithData<TEvent>>( event: TSentEvent['eventName'], data: TSentEvent['data'] ): void; sendEvent<TSentEvent extends TEvent>( eventName: TSentEvent['eventName'], data?: TSentEvent['data'] ): void { if (this.isDisposed) return; // console.group(); // console.log('sendEvent(%s, %s)', this.state.stateName, eventName, data); this.pendingExternalEvents.push({ eventName, data } as TEvent); if (!this.handlingEvents) { this.processEvents(); } } private processEvents() { if (this.handlingEvents) { throw new Error( 'Invariant violation: processEvents should never be called while already processing events.' ); } this.handlingEvents = true; while ( !this.isDisposed && (this.pendingExternalEvents.length || this.pendingInternalEvents.length) ) { while (!this.isDisposed && this.pendingInternalEvents.length) { const event = this.pendingInternalEvents.shift() as TEvent; this.onEventEmitter.fire(event); const currentStateDef = this.states.states[ this.mutableState.stateName as TState['stateName'] ]; // While the current state might not have a handler, there may be a global // handler. const handler = currentStateDef.onEvent?.[event.eventName as TEvent['eventName']] || this.states.onEvent?.[event.eventName as TEvent['eventName']]; if (handler) { const state = this.state; handler({ event: event as any, registerDisposable: this.stateDisposer.add.bind(this.stateDisposer), sendEvent: this.sendEventInternal.bind(this), state: state as any, transitionTo: this.transitionTo.bind(this), }); } } while (!this.isDisposed && this.pendingExternalEvents.length) { // Move external events into the internal event queue for the next tick // of the outer loop. this.pendingInternalEvents.push(this.pendingExternalEvents.pop()!); } } this.handlingEvents = false; } private sendEventInternal<TSentEvent extends EventWithoutData<TEvent>>( event: TSentEvent['eventName'] ): void; private sendEventInternal<TSentEvent extends EventWithData<TEvent>>( event: TSentEvent['eventName'], data: TSentEvent['data'] ): void; private sendEventInternal<TSentEvent extends TEvent>( eventName: TSentEvent['eventName'], data?: TSentEvent['data'] ): void { if (this.isDisposed) return; this.pendingInternalEvents.push({ eventName, data } as TEvent); if (!this.handlingEvents) { this.processEvents(); } } private transitionTo<TTargetState extends TState, TTriggeringEvent extends TEvent>( state: TTargetState, event: TTriggeringEvent ) { const fromStateConfig = this.states.states[this.mutableState.stateName as TState['stateName']]; const nextStateConfig = this.states.states[state.stateName as TState['stateName']]; const fromState = { ...this.mutableState }; this.mutableState = { ...state }; this.onStateChangeEmitter.fire(this.state); if (state.stateName !== fromState.stateName) { this.stateDisposer.clear(); if (fromStateConfig.onExit) { fromStateConfig.onExit({ event, state: state as any, }); } const onEnterDef = nextStateConfig.onEnter; if (onEnterDef) { let onEnterHandler: | OnEnterHandlerFunction<TState, TEvent, TState['stateName']> | undefined = undefined; if (typeof onEnterDef === 'string') { onEnterHandler = this.actions[onEnterDef]; } else if (typeof onEnterDef === 'function') { onEnterHandler = onEnterDef; } if (!onEnterHandler) { // TODO: Should we warn / error? return; } onEnterHandler({ event, registerDisposable: this.stateDisposer.add.bind(this.stateDisposer), sendEvent: this.sendEventInternal.bind(this), state: state as any, transitionTo: this.transitionTo.bind(this), }); } } } }
the_stack
import * as Gio from "@gi-types/gio"; import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export function error_quark(): GLib.Quark; export function identity_from_string(str: string): Identity | null; export function implicit_authorization_from_string( string: string, out_implicit_authorization: ImplicitAuthorization ): boolean; export function implicit_authorization_to_string(implicit_authorization: ImplicitAuthorization): string; export function subject_from_string(str: string): Subject; export class Error extends GLib.Error { static $gtype: GObject.GType<Error>; constructor(options: { message: string; code: number }); constructor(copy: Error); // Properties static FAILED: number; static CANCELLED: number; static NOT_SUPPORTED: number; static NOT_AUTHORIZED: number; // Members static quark(): GLib.Quark; } export namespace ImplicitAuthorization { export const $gtype: GObject.GType<ImplicitAuthorization>; } export enum ImplicitAuthorization { UNKNOWN = -1, NOT_AUTHORIZED = 0, AUTHENTICATION_REQUIRED = 1, ADMINISTRATOR_AUTHENTICATION_REQUIRED = 2, AUTHENTICATION_REQUIRED_RETAINED = 3, ADMINISTRATOR_AUTHENTICATION_REQUIRED_RETAINED = 4, AUTHORIZED = 5, } export namespace AuthorityFeatures { export const $gtype: GObject.GType<AuthorityFeatures>; } export enum AuthorityFeatures { NONE = 0, TEMPORARY_AUTHORIZATION = 1, } export namespace CheckAuthorizationFlags { export const $gtype: GObject.GType<CheckAuthorizationFlags>; } export enum CheckAuthorizationFlags { NONE = 0, ALLOW_USER_INTERACTION = 1, } export module ActionDescription { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ActionDescription extends GObject.Object { static $gtype: GObject.GType<ActionDescription>; constructor(properties?: Partial<ActionDescription.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ActionDescription.ConstructorProperties>, ...args: any[]): void; // Members get_action_id(): string; get_annotation(key: string): string | null; get_annotation_keys(): string[]; get_description(): string; get_icon_name(): string; get_implicit_active(): ImplicitAuthorization; get_implicit_any(): ImplicitAuthorization; get_implicit_inactive(): ImplicitAuthorization; get_message(): string; get_vendor_name(): string; get_vendor_url(): string; } export module Authority { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend_features: AuthorityFeatures; backendFeatures: AuthorityFeatures; backend_name: string; backendName: string; backend_version: string; backendVersion: string; owner: string; } } export class Authority extends GObject.Object implements Gio.AsyncInitable<Authority>, Gio.Initable { static $gtype: GObject.GType<Authority>; constructor(properties?: Partial<Authority.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Authority.ConstructorProperties>, ...args: any[]): void; // Properties backend_features: AuthorityFeatures; backendFeatures: AuthorityFeatures; backend_name: string; backendName: string; backend_version: string; backendVersion: string; owner: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "changed", callback: (_source: this) => void): number; connect_after(signal: "changed", callback: (_source: this) => void): number; emit(signal: "changed"): void; // Members authentication_agent_response( cookie: string, identity: Identity, cancellable?: Gio.Cancellable | null ): Promise<boolean>; authentication_agent_response( cookie: string, identity: Identity, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; authentication_agent_response( cookie: string, identity: Identity, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; authentication_agent_response_finish(res: Gio.AsyncResult): boolean; authentication_agent_response_sync( cookie: string, identity: Identity, cancellable?: Gio.Cancellable | null ): boolean; check_authorization( subject: Subject, action_id: string, details: Details | null, flags: CheckAuthorizationFlags, cancellable?: Gio.Cancellable | null ): Promise<AuthorizationResult>; check_authorization( subject: Subject, action_id: string, details: Details | null, flags: CheckAuthorizationFlags, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; check_authorization( subject: Subject, action_id: string, details: Details | null, flags: CheckAuthorizationFlags, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<AuthorizationResult> | void; check_authorization_finish(res: Gio.AsyncResult): AuthorizationResult; check_authorization_sync( subject: Subject, action_id: string, details: Details | null, flags: CheckAuthorizationFlags, cancellable?: Gio.Cancellable | null ): AuthorizationResult; enumerate_actions(cancellable?: Gio.Cancellable | null): Promise<ActionDescription[]>; enumerate_actions(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; enumerate_actions( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<ActionDescription[]> | void; enumerate_actions_finish(res: Gio.AsyncResult): ActionDescription[]; enumerate_actions_sync(cancellable?: Gio.Cancellable | null): ActionDescription[]; enumerate_temporary_authorizations( subject: Subject, cancellable?: Gio.Cancellable | null ): Promise<TemporaryAuthorization[]>; enumerate_temporary_authorizations( subject: Subject, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; enumerate_temporary_authorizations( subject: Subject, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<TemporaryAuthorization[]> | void; enumerate_temporary_authorizations_finish(res: Gio.AsyncResult): TemporaryAuthorization[]; enumerate_temporary_authorizations_sync( subject: Subject, cancellable?: Gio.Cancellable | null ): TemporaryAuthorization[]; get_backend_features(): AuthorityFeatures; get_backend_name(): string; get_backend_version(): string; get_owner(): string | null; register_authentication_agent( subject: Subject, locale: string, object_path: string, cancellable?: Gio.Cancellable | null ): Promise<boolean>; register_authentication_agent( subject: Subject, locale: string, object_path: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; register_authentication_agent( subject: Subject, locale: string, object_path: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; register_authentication_agent_finish(res: Gio.AsyncResult): boolean; register_authentication_agent_sync( subject: Subject, locale: string, object_path: string, cancellable?: Gio.Cancellable | null ): boolean; register_authentication_agent_with_options( subject: Subject, locale: string, object_path: string, options?: GLib.Variant | null, cancellable?: Gio.Cancellable | null ): Promise<boolean>; register_authentication_agent_with_options( subject: Subject, locale: string, object_path: string, options: GLib.Variant | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; register_authentication_agent_with_options( subject: Subject, locale: string, object_path: string, options?: GLib.Variant | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; register_authentication_agent_with_options_finish(res: Gio.AsyncResult): boolean; register_authentication_agent_with_options_sync( subject: Subject, locale: string, object_path: string, options?: GLib.Variant | null, cancellable?: Gio.Cancellable | null ): boolean; revoke_temporary_authorization_by_id(id: string, cancellable?: Gio.Cancellable | null): Promise<boolean>; revoke_temporary_authorization_by_id( id: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; revoke_temporary_authorization_by_id( id: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; revoke_temporary_authorization_by_id_finish(res: Gio.AsyncResult): boolean; revoke_temporary_authorization_by_id_sync(id: string, cancellable?: Gio.Cancellable | null): boolean; revoke_temporary_authorizations(subject: Subject, cancellable?: Gio.Cancellable | null): Promise<boolean>; revoke_temporary_authorizations( subject: Subject, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; revoke_temporary_authorizations( subject: Subject, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; revoke_temporary_authorizations_finish(res: Gio.AsyncResult): boolean; revoke_temporary_authorizations_sync(subject: Subject, cancellable?: Gio.Cancellable | null): boolean; unregister_authentication_agent( subject: Subject, object_path: string, cancellable?: Gio.Cancellable | null ): Promise<boolean>; unregister_authentication_agent( subject: Subject, object_path: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; unregister_authentication_agent( subject: Subject, object_path: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; unregister_authentication_agent_finish(res: Gio.AsyncResult): boolean; unregister_authentication_agent_sync( subject: Subject, object_path: string, cancellable?: Gio.Cancellable | null ): boolean; static get(): Authority; static get_async(cancellable?: Gio.Cancellable | null): Promise<Authority>; static get_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Authority> | null): void; static get_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Authority> | null ): Promise<Authority> | void; static get_finish(res: Gio.AsyncResult): Authority; static get_sync(cancellable?: Gio.Cancellable | null): Authority; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): Authority; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module AuthorizationResult { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class AuthorizationResult extends GObject.Object { static $gtype: GObject.GType<AuthorizationResult>; constructor(properties?: Partial<AuthorizationResult.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthorizationResult.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](is_authorized: boolean, is_challenge: boolean, details?: Details | null): AuthorizationResult; // Members get_details(): Details | null; get_dismissed(): boolean; get_is_authorized(): boolean; get_is_challenge(): boolean; get_retains_authorization(): boolean; get_temporary_authorization_id(): string | null; } export module Details { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Details extends GObject.Object { static $gtype: GObject.GType<Details>; constructor(properties?: Partial<Details.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Details.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Details; // Members get_keys(): string[] | null; insert(key: string, value?: string | null): void; lookup(key: string): string | null; } export module Permission { export interface ConstructorProperties extends Gio.Permission.ConstructorProperties { [key: string]: any; action_id: string; actionId: string; subject: Subject; } } export class Permission extends Gio.Permission implements Gio.AsyncInitable<Permission>, Gio.Initable { static $gtype: GObject.GType<Permission>; constructor(properties?: Partial<Permission.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Permission.ConstructorProperties>, ...args: any[]): void; // Properties action_id: string; actionId: string; subject: Subject; // Constructors static new_finish(res: Gio.AsyncResult): Permission; static new_finish(...args: never[]): never; static new_sync(action_id: string, subject?: Subject | null, cancellable?: Gio.Cancellable | null): Permission; // Members get_action_id(): string; get_subject(): Subject; static new(action_id: string, subject?: Subject | null, cancellable?: Gio.Cancellable | null): Promise<Permission>; static new( action_id: string, subject: Subject | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Permission> | null ): void; static new( action_id: string, subject?: Subject | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Permission> | null ): Promise<Permission> | void; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): Permission; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module SystemBusName { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; } } export class SystemBusName extends GObject.Object implements Subject { static $gtype: GObject.GType<SystemBusName>; constructor(properties?: Partial<SystemBusName.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SystemBusName.ConstructorProperties>, ...args: any[]): void; // Properties name: string; // Members get_name(): string; get_process_sync(cancellable?: Gio.Cancellable | null): Subject | null; get_user_sync(cancellable?: Gio.Cancellable | null): UnixUser | null; set_name(name: string): void; static new(name: string): Subject; // Implemented Members equal(b: Subject): boolean; exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; exists_finish(res: Gio.AsyncResult): boolean; exists_sync(cancellable?: Gio.Cancellable | null): boolean; hash(): number; to_string(): string; vfunc_equal(b: Subject): boolean; vfunc_exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; vfunc_exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_exists_finish(res: Gio.AsyncResult): boolean; vfunc_exists_sync(cancellable?: Gio.Cancellable | null): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export module TemporaryAuthorization { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class TemporaryAuthorization extends GObject.Object { static $gtype: GObject.GType<TemporaryAuthorization>; constructor(properties?: Partial<TemporaryAuthorization.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<TemporaryAuthorization.ConstructorProperties>, ...args: any[]): void; // Members get_action_id(): string; get_id(): string; get_subject(): Subject; get_time_expires(): number; get_time_obtained(): number; } export module UnixGroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; gid: number; } } export class UnixGroup extends GObject.Object implements Identity { static $gtype: GObject.GType<UnixGroup>; constructor(properties?: Partial<UnixGroup.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixGroup.ConstructorProperties>, ...args: any[]): void; // Properties gid: number; // Members get_gid(): number; set_gid(gid: number): void; static new(gid: number): Identity; static new_for_name(name: string): Identity; // Implemented Members equal(b: Identity): boolean; hash(): number; to_string(): string; vfunc_equal(b: Identity): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export module UnixNetgroup { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; } } export class UnixNetgroup extends GObject.Object implements Identity { static $gtype: GObject.GType<UnixNetgroup>; constructor(properties?: Partial<UnixNetgroup.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixNetgroup.ConstructorProperties>, ...args: any[]): void; // Properties name: string; // Members get_name(): string; set_name(name: string): void; static new(name: string): Identity; // Implemented Members equal(b: Identity): boolean; hash(): number; to_string(): string; vfunc_equal(b: Identity): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export module UnixProcess { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; pid: number; start_time: number; startTime: number; uid: number; } } export class UnixProcess extends GObject.Object implements Subject { static $gtype: GObject.GType<UnixProcess>; constructor(properties?: Partial<UnixProcess.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixProcess.ConstructorProperties>, ...args: any[]): void; // Properties pid: number; start_time: number; startTime: number; uid: number; // Members get_owner(): number; get_pid(): number; get_start_time(): number; get_uid(): number; set_pid(pid: number): void; set_start_time(start_time: number): void; set_uid(uid: number): void; static new(pid: number): Subject; static new_for_owner(pid: number, start_time: number, uid: number): Subject; static new_full(pid: number, start_time: number): Subject; // Implemented Members equal(b: Subject): boolean; exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; exists_finish(res: Gio.AsyncResult): boolean; exists_sync(cancellable?: Gio.Cancellable | null): boolean; hash(): number; to_string(): string; vfunc_equal(b: Subject): boolean; vfunc_exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; vfunc_exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_exists_finish(res: Gio.AsyncResult): boolean; vfunc_exists_sync(cancellable?: Gio.Cancellable | null): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export module UnixSession { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; pid: number; session_id: string; sessionId: string; } } export class UnixSession extends GObject.Object implements Gio.AsyncInitable<UnixSession>, Gio.Initable, Subject { static $gtype: GObject.GType<UnixSession>; constructor(properties?: Partial<UnixSession.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixSession.ConstructorProperties>, ...args: any[]): void; // Properties pid: number; session_id: string; sessionId: string; // Members get_session_id(): string; set_session_id(session_id: string): void; static new(session_id: string): Subject; static new_for_process(pid: number, cancellable?: Gio.Cancellable | null): Promise<Subject | null>; static new_for_process( pid: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<UnixSession> | null ): void; static new_for_process( pid: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<UnixSession> | null ): Promise<Subject | null> | void; static new_for_process_finish(res: Gio.AsyncResult): Subject | null; static new_for_process_sync(pid: number, cancellable?: Gio.Cancellable | null): Subject | null; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): UnixSession; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; equal(b: Subject): boolean; exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; exists_finish(res: Gio.AsyncResult): boolean; exists_sync(cancellable?: Gio.Cancellable | null): boolean; hash(): number; to_string(): string; vfunc_equal(b: Subject): boolean; vfunc_exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; vfunc_exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_exists_finish(res: Gio.AsyncResult): boolean; vfunc_exists_sync(cancellable?: Gio.Cancellable | null): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export module UnixUser { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; uid: number; } } export class UnixUser extends GObject.Object implements Identity { static $gtype: GObject.GType<UnixUser>; constructor(properties?: Partial<UnixUser.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<UnixUser.ConstructorProperties>, ...args: any[]): void; // Properties uid: number; // Members get_name(): string | null; get_uid(): number; set_uid(uid: number): void; static new(uid: number): Identity; static new_for_name(name: string): Identity | null; // Implemented Members equal(b: Identity): boolean; hash(): number; to_string(): string; vfunc_equal(b: Identity): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export interface IdentityNamespace { $gtype: GObject.GType<Identity>; prototype: IdentityPrototype; from_string(str: string): Identity | null; } export type Identity = IdentityPrototype; export interface IdentityPrototype extends GObject.Object { // Members equal(b: Identity): boolean; hash(): number; to_string(): string; vfunc_equal(b: Identity): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export const Identity: IdentityNamespace; export interface SubjectNamespace { $gtype: GObject.GType<Subject>; prototype: SubjectPrototype; from_string(str: string): Subject; } export type Subject = SubjectPrototype; export interface SubjectPrototype extends GObject.Object { // Members equal(b: Subject): boolean; exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; exists_finish(res: Gio.AsyncResult): boolean; exists_sync(cancellable?: Gio.Cancellable | null): boolean; hash(): number; to_string(): string; vfunc_equal(b: Subject): boolean; vfunc_exists(cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_exists(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; vfunc_exists( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_exists_finish(res: Gio.AsyncResult): boolean; vfunc_exists_sync(cancellable?: Gio.Cancellable | null): boolean; vfunc_hash(): number; vfunc_to_string(): string; } export const Subject: SubjectNamespace;
the_stack
import { html } from 'lit-html'; import { $$ } from 'common-sk/modules/dom'; import { diffDate, localeTime } from 'common-sk/modules/human'; import { define } from 'elements-sk/define'; import 'elements-sk/styles/buttons'; import 'elements-sk/styles/select'; import 'elements-sk/styles/table'; import 'elements-sk/tabs-panel-sk'; import 'elements-sk/tabs-sk'; import { ElementSk } from '../../../infra-sk/modules/ElementSk'; import { LoginTo } from '../../../infra-sk/modules/login'; import { truncate } from '../../../infra-sk/modules/string'; import { AutoRollConfig, AutoRollCL, AutoRollService, AutoRollStatus, CreateManualRollResponse, GetAutoRollService, ManualRoll, ManualRoll_Result, ManualRoll_Status, Mode, Revision, Strategy, TryJob, SetModeResponse, SetStrategyResponse, GetStatusResponse, AutoRollCL_Result, TryJob_Result, } from '../rpc'; interface RollCandidate { revision: Revision; roll: ManualRoll | null; } export class ARBStatusSk extends ElementSk { private static template = (ele: ARBStatusSk) => (!ele.status ? html`` : html` <tabs-sk> <button value="status">Roller Status</button> <button value="manual">Trigger Manual Rolls</button> </tabs-sk> ${!ele.editRights ? html` <div id="pleaseLoginMsg" class="big">${ele.pleaseLoginMsg}</div> ` : html`` } <tabs-panel-sk selected="0"> <div class="status"> <div id="loadstatus"> Reload (s) <input id="refreshInterval" type="number" value="${ele.refreshInterval}" label="Reload (s)" @input=${ele.reloadChanged} ></input> Last loaded at <span>${localeTime(ele.lastLoaded)}</span> </div> <table> ${ele.status.config?.parentWaterfall ? html` <tr> <td class="nowrap">Parent Repo Build Status</td> <td class="nowrap unknown"> <span> <a href="${ele.status.config.parentWaterfall}" target="_blank" > ${ele.status.config.parentWaterfall} </a> </span> </td> </tr> ` : html`` } <tr> <td class="nowrap">Current Mode:</td> <td class="nowrap unknown"> <span class="big">${ele.status.mode?.mode .toLowerCase() .replace('_', ' ')}</span> </td> </tr> <tr> <td class="nowrap">Set By:</td> <td class="nowrap unknown"> ${ele.status.mode?.user} ${ele.status.mode ? `at ${localeTime(new Date(ele.status.mode!.time!))}` : html`` } ${ele.status.mode?.message ? html`: ${ele.status.mode.message}` : html`` } </td> </tr> <tr> <td class="nowrap">Change Mode:</td> <td class="nowrap"> ${Object.keys(Mode).map((mode: string) => (mode === ele.status?.mode?.mode ? '' : html` <button @click="${() => { ele.modeButtonPressed(mode); }}" ?disabled="${!ele.editRights || ele.modeChangePending}" title="${ele.editRights ? 'Change the mode.' : ele.pleaseLoginMsg}" value="${mode}" > ${ele.status?.mode?.mode ? ele.getModeButtonLabel(ele.status.mode.mode, mode) : ''} </button> `))} </td> </tr> <tr> <td class="nowrap">Status:</td> <td class="nowrap"> <span class="${ele.statusClass(ele.status.status)}"> <span class="big">${ele.status.status}</span> </span> ${ele.status.status.indexOf('throttle') >= 0 ? html` <span >until ${localeTime(new Date(ele.status.throttledUntil!))}</span > <button @click="${ele.unthrottle}" ?disabled="${!ele.editRights}" title="${ele.editRights ? 'Unthrottle the roller.' : ele.pleaseLoginMsg}" > Force Unthrottle </button> ` : html`` } ${ele.status.status.indexOf('waiting for roll window') >= 0 ? html` <span>until ${localeTime(ele.rollWindowStart)}</span> ` : html`` } </td> </tr> ${ele.editRights && ele.status.error ? html` <tr> <td class="nowrap">Error:</td> <td><pre>${ele.status.error}</pre></td> </tr> ` : html`` } ${ele.status.config?.childBugLink ? html` <tr> <td class="nowrap">File a bug in ${ele.status.miniStatus?.childName}</td> <td> <a href="${ele.status.config.childBugLink}" target="_blank" class="small" > file bug </a> </td> </tr> ` : html`` } ${ele.status.config?.parentBugLink ? html` <tr> <td class="nowrap">File a bug in ${ele.status.miniStatus?.parentName}</td> <td> <a href="${ele.status.config.parentBugLink}" target="_blank" class="small" > file bug </a> </td> </tr> ` : html`` } <tr> <td class="nowrap">Current Roll:</td> <td> <div> ${ele.status.currentRoll ? html` <a href="${ele.issueURL(ele.status.currentRoll)}" class="big" target="_blank" > ${ele.status.currentRoll.subject} </a> ` : html`<span>(none)</span>` } </div> <div> ${ele.status.currentRoll && ele.status.currentRoll.tryJobs ? ele.status.currentRoll.tryJobs.map( (tryResult) => html` <div class="trybot"> ${tryResult.url ? html` <a href="${tryResult.url}" class="${ele.trybotClass(tryResult)}" target="_blank" > ${tryResult.name} </a> ` : html` <span class="nowrap" class="${ele.trybotClass(tryResult)}" > ${tryResult.name} </span> `} ${tryResult.category === 'cq' ? html`` : html` <span class="nowrap small" >(${tryResult.category})</span > `} </div> `, ) : html`` } </div> </td> </tr> ${ele.status.lastRoll ? html` <tr> <td class="nowrap">Previous roll result:</td> <td> <span class="${ele.rollClass(ele.status.lastRoll)}"> ${ele.rollResult(ele.status.lastRoll)} </span> <a href="${ele.issueURL(ele.status.lastRoll)}" target="_blank" class="small" > (detail) </a> </td> </tr> ` : html`` } <tr> <td class="nowrap">History:</td> <td> <table> <tr> <th>Roll</th> <th>Last Modified</th> <th>Result</th> </tr> ${ele.status.recentRolls?.map( (roll: AutoRollCL) => html` <tr> <td> <a href="${ele.issueURL(roll)}" target="_blank" >${roll.subject}</a > </td> <td>${diffDate(roll.modified!)} ago</td> <td> <span class="${ele.rollClass(roll)}" >${ele.rollResult(roll)}</span > </td> </tr> `, )} </table> </td> </tr> <tr> <td class="nowrap">Full History:</td> <td> <a href="${ele.status.fullHistoryUrl}" target="_blank"> ${ele.status.fullHistoryUrl} </a> </td> </tr> <tr> <td class="nowrap">Strategy for choosing next roll revision:</td> <td class="nowrap"> <select id="strategySelect" ?disabled="${!ele.editRights || ele.strategyChangePending}" title="${ele.editRights ? 'Change the strategy for choosing the next revision to roll.' : ele.pleaseLoginMsg }" @change="${ele.selectedStrategyChanged}"> ${Object.keys(Strategy).map( (strategy: string) => html` <option value="${strategy}" ?selected="${strategy === ele.status?.strategy?.strategy}" > ${strategy.toLowerCase().replace('_', ' ')} </option> `, )} </select> </td> </tr> <tr> <td class="nowrap">Set By:</td> <td class="nowrap unknown"> ${ele.status.strategy?.user} ${ele.status.strategy ? `at ${localeTime(new Date(ele.status.strategy!.time!))}` : html`` } ${ele.status.strategy?.message ? html`: ${ele.status.strategy.message}` : html`` } </td> </tr> </table> </div> <div class="manual"> <table> ${ele.status.config?.supportsManualRolls ? html` ${!ele.rollCandidates ? html` The roller is up to date; there are no revisions which could be manually rolled. ` : html`` } <tr> <th>Revision</th> <th>Description</th> <th>Timestamp</th> <th>Requester</th> <th>Requested at</th> <th>Roll</th> </tr> ${ele.rollCandidates.map( (rollCandidate) => html` <tr class="rollCandidate"> <td> ${rollCandidate.revision.url ? html` <a href="${rollCandidate.revision.url}" target="_blank"> ${rollCandidate.revision.display} </a> ` : html` ${rollCandidate.revision.display} `} </td> <td> ${rollCandidate.revision.description ? truncate(rollCandidate.revision.description, 100) : html``} </td> <td> ${rollCandidate.revision.time ? localeTime(new Date(rollCandidate.revision.time!)) : html``} </td> <td> ${rollCandidate.roll ? rollCandidate.roll.requester : html``} </td> <td> ${rollCandidate.roll ? localeTime(new Date(rollCandidate.roll.timestamp!)) : html``} </td> <td> ${rollCandidate.roll && rollCandidate.roll.url ? html` <a href="${rollCandidate.roll.url}" , target="_blank"> ${rollCandidate.roll.url} </a> ${rollCandidate.roll.dryRun ? html` [dry-run]` : html``} ` : html``} ${!!rollCandidate.roll && !rollCandidate.roll.url && rollCandidate.roll.status ? rollCandidate.roll.status : html``} ${!rollCandidate.roll ? html` <button @click="${() => { ele.requestManualRoll(rollCandidate.revision.id, true); }}" class="requestRoll" ?disabled=${!ele.editRights} title="${ele.editRights ? 'Request a dry-run to this revision.' : ele.pleaseLoginMsg}" > Request Dry-Run </button> <button @click="${() => { ele.requestManualRoll(rollCandidate.revision.id, false); }}" class="requestRoll" ?disabled=${!ele.editRights} title="${ele.editRights ? 'Request a roll to this revision.' : ele.pleaseLoginMsg}" > Request Roll </button> ` : html``} ${!!rollCandidate.roll && !!rollCandidate.roll.result ? html` <span class="${ele.manualRollResultClass( rollCandidate.roll, )}" > ${rollCandidate.roll.result == ManualRoll_Result.UNKNOWN ? html`` : rollCandidate.roll.result} </span> ` : html``} </td> </tr> `, )} <tr class="rollCandidate"> <td> <input id="manualRollRevInput" label="type revision/ref"></input> </td> <td><!-- no description --></td> <td><!-- no revision timestamp --></td> <td><!-- no requester --></td> <td><!-- no request timestamp --></td> <td> <button @click="${() => { ele.requestManualRoll( $$<HTMLInputElement>('#manualRollRevInput')!.value, true, ); }}" class="requestRoll" ?disabled=${!ele.editRights} title="${ele.editRights ? 'Request a dry-run to this revision.' : ele.pleaseLoginMsg }"> Request Dry-Run </button> <button @click="${() => { ele.requestManualRoll( $$<HTMLInputElement>('#manualRollRevInput')!.value, false, ); }}" class="requestRoll" ?disabled=${!ele.editRights} title="${ele.editRights ? 'Request a roll to this revision.' : ele.pleaseLoginMsg }"> Request Roll </button> </td> </tr> ` : html` This roller does not support manual rolls. If you want this feature, update the config file for the roller to enable it. Note that some rollers cannot support manual rolls for technical reasons. ` } </table> </div> </tabs-panel-sk> <dialog id="modeChangeDialog" class=surface-themes-sk> <h2>Enter a message:</h2> <input type="text" id="modeChangeMsgInput"></input> <button @click="${() => { ele.changeMode(false); }}">Cancel</button> <button @click="${() => { ele.changeMode(true); }}">Submit</button> </dialog> <dialog id="strategyChangeDialog" class=surface-themes-sk> <h2>Enter a message:</h2> <input type="text" id="strategyChangeMsgInput"></input> <button @click="${() => { ele.changeStrategy(false); }}">Cancel</button> <button @click="${() => { ele.changeStrategy(true); }}">Submit</button> </dialog> `); private editRights: boolean = false; private lastLoaded: Date = new Date(0); private modeChangePending: boolean = false; private readonly pleaseLoginMsg = 'Please login to make changes.'; private refreshInterval = 60; private rollCandidates: RollCandidate[] = []; private rollWindowStart: Date = new Date(0); private rpc: AutoRollService = GetAutoRollService(this); private selectedMode: string = ''; private status: AutoRollStatus | null = null; private strategyChangePending: boolean = false; private timeout: number = 0; constructor() { super(ARBStatusSk.template); } connectedCallback() { super.connectedCallback(); this._upgradeProperty('roller'); this._render(); LoginTo('/loginstatus/').then((loginstatus: any) => { this.editRights = loginstatus.IsAGoogler; this._render(); }); this.reload(); } get roller() { return this.getAttribute('roller') || ''; } set roller(v: string) { this.setAttribute('roller', v); this.reload(); } private modeButtonPressed(mode: string) { if (mode === this.status?.mode?.mode) { return; } this.selectedMode = mode; $$<HTMLDialogElement>('#modeChangeDialog', this)!.showModal(); } private changeMode(submit: boolean) { $$<HTMLDialogElement>('#modeChangeDialog', this)!.close(); if (!submit) { this.selectedMode = ''; return; } const modeChangeMsgInput = <HTMLInputElement>( $$('#modeChangeMsgInput', this) ); if (!modeChangeMsgInput) { return; } this.modeChangePending = true; this.rpc .setMode({ message: modeChangeMsgInput.value, mode: Mode[<keyof typeof Mode> this.selectedMode], rollerId: this.roller, }) .then( (resp: SetModeResponse) => { this.modeChangePending = false; modeChangeMsgInput.value = ''; this.update(resp.status!); }, () => { this.modeChangePending = false; this._render(); }, ); } private changeStrategy(submit: boolean) { $$<HTMLDialogElement>('#strategyChangeDialog', this)!.close(); const strategySelect = <HTMLSelectElement>$$('#strategySelect'); const strategyChangeMsgInput = <HTMLInputElement>( $$('#strategyChangeMsgInput') ); if (!submit) { if (!!strategySelect && !!this.status?.strategy) { strategySelect.value = this.status?.strategy.strategy; } return; } if (!strategyChangeMsgInput || !strategySelect) { return; } this.strategyChangePending = true; this.rpc .setStrategy({ message: strategyChangeMsgInput.value, rollerId: this.roller, strategy: Strategy[<keyof typeof Strategy>strategySelect.value], }) .then( (resp: SetStrategyResponse) => { this.strategyChangePending = false; strategyChangeMsgInput.value = ''; this.update(resp.status!); }, () => { this.strategyChangePending = false; if (this.status?.strategy?.strategy) { strategySelect!.value = this.status.strategy.strategy; } this._render(); }, ); } // computeRollWindowStart returns a string indicating when the configured // roll window will start. If errors are encountered, in particular those // relating to parsing the roll window, the returned string will contain // the error. private computeRollWindowStart(config: AutoRollConfig): Date { if (!config || !config.timeWindow) { return new Date(); } // TODO(borenet): This duplicates code in the go/time_window package. // parseDayTime returns a 2-element array containing the hour and // minutes as ints. Throws an error (string) if the given string cannot // be parsed as hours and minutes. const parseDayTime = function(s: string) { const timeSplit = s.split(':'); if (timeSplit.length !== 2) { throw `Expected time format "hh:mm", not ${s}`; } const hours = parseInt(timeSplit[0]); if (hours < 0 || hours >= 24) { throw `Hours must be between 0-23, not ${timeSplit[0]}`; } const minutes = parseInt(timeSplit[1]); if (minutes < 0 || minutes >= 60) { throw `Minutes must be between 0-59, not ${timeSplit[1]}`; } return [hours, minutes]; }; // Parse multiple day/time windows, eg. M-W 00:00-04:00; Th-F 00:00-02:00 const windows = []; const split = config.timeWindow.split(';'); for (let i = 0; i < split.length; i++) { const dayTimeWindow = split[i].trim(); // Parse individual day/time window, eg. M-W 00:00-04:00 const windowSplit = dayTimeWindow.split(' '); if (windowSplit.length !== 2) { console.error(`expected format "D hh:mm", not ${dayTimeWindow}`); return new Date(); } const dayExpr = windowSplit[0].trim(); const timeExpr = windowSplit[1].trim(); // Parse the starting and ending times. const timeExprSplit = timeExpr.split('-'); if (timeExprSplit.length !== 2) { console.error(`expected format "hh:mm-hh:mm", not ${timeExpr}`); return new Date(); } let startTime; try { startTime = parseDayTime(timeExprSplit[0]); } catch (e) { return e; } let endTime; try { endTime = parseDayTime(timeExprSplit[1]); } catch (e) { return e; } // Parse the day(s). const allDays = ['Su', 'M', 'Tu', 'W', 'Th', 'F', 'Sa']; const days = []; // "*" means every day. if (dayExpr === '*') { days.push(...allDays.map((_, i) => i)); } else { const rangesSplit = dayExpr.split(','); for (let i = 0; i < rangesSplit.length; i++) { const rangeSplit = rangesSplit[i].split('-'); if (rangeSplit.length === 1) { const day = allDays.indexOf(rangeSplit[0]); if (day === -1) { console.error(`Unknown day ${rangeSplit[0]}`); return new Date(); } days.push(day); } else if (rangeSplit.length === 2) { const startDay = allDays.indexOf(rangeSplit[0]); if (startDay === -1) { console.error(`Unknown day ${rangeSplit[0]}`); return new Date(); } let endDay = allDays.indexOf(rangeSplit[1]); if (endDay === -1) { console.error(`Unknown day ${rangeSplit[1]}`); return new Date(); } if (endDay < startDay) { endDay += 7; } for (let day = startDay; day <= endDay; day++) { days.push(day % 7); } } else { console.error(`Invalid day expression ${rangesSplit[i]}`); return new Date(); } } } // Add the windows to the list. for (let i = 0; i < days.length; i++) { windows.push({ day: days[i], start: startTime, end: endTime, }); } } // For each window, find the timestamp at which it opens next. const now = new Date().getTime(); const openTimes = windows.map((w) => { let next = new Date(now); next.setUTCHours(w.start[0], w.start[1], 0, 0); const dayOffsetMs = (w.day - next.getUTCDay()) * 24 * 60 * 60 * 1000; next = new Date(next.getTime() + dayOffsetMs); if (next.getTime() < now) { // If we've missed this week's window, bump forward a week. next = new Date(next.getTime() + 7 * 24 * 60 * 60 * 1000); } return next; }); // Pick the next window. openTimes.sort((a, b) => a.getTime() - b.getTime()); const rollWindowStart = openTimes[0].toString(); return openTimes[0]; } private issueURL(roll: AutoRollCL): string { if (roll) { return (this.status?.issueUrlBase || '') + roll.id; } return ''; } private getModeButtonLabel(currentMode: Mode, mode: string) { switch (currentMode) { case Mode.RUNNING: switch (mode) { case Mode.STOPPED: return 'stop'; case Mode.DRY_RUN: return 'switch to dry run'; } case Mode.STOPPED: switch (mode) { case Mode.RUNNING: return 'resume'; case Mode.DRY_RUN: return 'switch to dry run'; } case Mode.DRY_RUN: switch (mode) { case Mode.RUNNING: return 'switch to normal mode'; case Mode.STOPPED: return 'stop'; } } } private reloadChanged() { const refreshIntervalInput = <HTMLInputElement>( $$('refreshIntervalInput', this) ); if (refreshIntervalInput) { this.refreshInterval = refreshIntervalInput.valueAsNumber; this.resetTimeout(); } } private resetTimeout() { if (this.timeout) { window.clearTimeout(this.timeout); } if (this.refreshInterval > 0) { this.timeout = window.setTimeout(() => { this.reload(); }, this.refreshInterval * 1000); } } private reload() { if (!this.roller) { return; } console.log(`Loading status for ${this.roller}...`); this.rpc .getStatus({ rollerId: this.roller, }) .then((resp: GetStatusResponse) => { this.update(resp.status!); this.resetTimeout(); }) .catch((err: any) => { this.resetTimeout(); }); } private manualRollResultClass(req: ManualRoll) { if (!req) { return ''; } switch (req.result) { case ManualRoll_Result.SUCCESS: return 'fg-success'; case ManualRoll_Result.FAILURE: return 'fg-failure'; default: return ''; } } private requestManualRoll(rev: string, dryRun: boolean) { // Make sure the user wants to proceed. let confirmMsg = 'Proceed with requesting manual '; if (dryRun) { confirmMsg += 'dry-run?' } else { confirmMsg += 'roll?' } const confirmed = window.confirm(confirmMsg); if (!confirmed) { return; } this.rpc .createManualRoll({ revision: rev, rollerId: this.roller, dryRun: dryRun, }) .then((resp: CreateManualRollResponse) => { const exist = this.rollCandidates.find( (r) => r.revision.id === resp.roll!.revision, ); if (exist) { exist.roll = resp.roll!; } else { this.rollCandidates.push({ revision: { description: '', display: resp.roll!.revision, id: resp.roll!.revision, time: '', url: '', }, roll: resp.roll!, }); } const manualRollRevInput = <HTMLInputElement>$$('#manualRollRevInput'); if (manualRollRevInput) { manualRollRevInput.value = ''; } this._render(); }); } private rollClass(roll: AutoRollCL) { if (!roll) { return 'unknown'; } switch (roll.result) { case AutoRollCL_Result.SUCCESS: return 'fg-success'; case AutoRollCL_Result.FAILURE: return 'fg-failure'; case AutoRollCL_Result.IN_PROGRESS: return 'fg-unknown'; case AutoRollCL_Result.DRY_RUN_SUCCESS: return 'fg-success'; case AutoRollCL_Result.DRY_RUN_FAILURE: return 'fg-failure'; case AutoRollCL_Result.DRY_RUN_IN_PROGRESS: return 'fg-unknown'; default: return 'fg-unknown'; } } private rollResult(roll: AutoRollCL) { if (!roll) { return 'unknown'; } return roll.result.toLowerCase().replace('_', ' '); } private statusClass(status: string) { // TODO(borenet): Status could probably be an enum. const statusClassMap: { [key: string]: string } = { idle: 'fg-unknown', active: 'fg-unknown', success: 'fg-success', failure: 'fg-failure', throttled: 'fg-failure', 'dry run idle': 'fg-unknown', 'dry run active': 'fg-unknown', 'dry run success': 'fg-success', 'dry run success; leaving open': 'fg-success', 'dry run failure': 'fg-failure', 'dry run throttled': 'fg-failure', stopped: 'fg-failure', }; return statusClassMap[status] || ''; } private selectedStrategyChanged() { if ( $$<HTMLSelectElement>('#strategySelect', this)!.value === this.status?.strategy?.strategy ) { return; } $$<HTMLDialogElement>('#strategyChangeDialog', this)!.showModal(); } private trybotClass(tryjob: TryJob) { switch (tryjob.result) { case TryJob_Result.SUCCESS: return 'fg-success'; case TryJob_Result.FAILURE: return 'fg-failure'; case TryJob_Result.CANCELED: return 'fg-failure'; default: return 'fg-unknown'; } } private unthrottle() { this.rpc.unthrottle({ rollerId: this.roller, }); } private update(status: AutoRollStatus) { const rollCandidates: RollCandidate[] = []; const manualByRev: { [key: string]: ManualRoll } = {}; if (status.notRolledRevisions) { if (status.manualRolls) { for (let i = 0; i < status.manualRolls.length; i++) { const req = status.manualRolls[i]; manualByRev[req.revision] = req; } } for (let i = 0; i < status.notRolledRevisions.length; i++) { const rev = status.notRolledRevisions[i]; const candidate: RollCandidate = { revision: rev, roll: null, }; let req = manualByRev[rev.id]; delete manualByRev[rev.id]; if ( !req && status.currentRoll && status.currentRoll.rollingTo === rev.id ) { req = { dryRun: false, id: '', noEmail: false, noResolveRevision: false, requester: 'autoroller', result: ManualRoll_Result.UNKNOWN, rollerId: this.roller, revision: '', status: ManualRoll_Status.PENDING, timestamp: status.currentRoll.created, url: this.issueURL(status.currentRoll), }; } candidate.roll = req; rollCandidates.push(candidate); } } for (const key in manualByRev) { const req = manualByRev[key]; const rev: Revision = { description: '', display: req.revision, id: req.revision, time: '', url: '', }; rollCandidates.push({ revision: rev, roll: req, }); } this.lastLoaded = new Date(); this.rollCandidates = rollCandidates; if (status.config) { this.rollWindowStart = this.computeRollWindowStart(status.config); } this.status = status; console.log('Loaded status.'); this._render(); } } define('arb-status-sk', ARBStatusSk);
the_stack
import { CfnParameter, Construct, StackProps, Stack, Duration, CfnCondition, Fn, CfnMapping, CfnOutput, Aws, } from '@aws-cdk/core'; import { Runtime, Code } from '@aws-cdk/aws-lambda'; import { Asset } from '@aws-cdk/aws-s3-assets'; import { SolutionHelper } from './solution-helper-construct'; import { CoreLambda } from './corelambda-construct'; import { LambdaToPolly } from './lambda-polly-construct'; import { CognitoApiLambda } from './cognito-api-lambdas-construct'; import { OrderPizzaLambdaDynamoDBTables } from './orderpizza-dynampdb-tables-construct'; import { CloudfrontStaticWebsite } from './cloudfront-static-website-construct'; import { LexLambdaDynamoDBTable } from './lexlambda-dynamodb-table-construct'; import { WriteApiKeyCustomResource } from './write-apikey-custom-resource-construct'; import { WeatherForecastToSSM } from './weather-forecast-lambda-ssm-construct'; import { WebClientCustomResource } from './web-client-custom-resource-construct'; import { LexCustomResource } from './custom-resource-lex-bot'; export interface ServerlessBotFrameworkStackProps extends StackProps { readonly solutionID: string; readonly solutionName: string; } export class ServerlessBotFrameworkStack extends Stack { constructor( scope: Construct, id: string, props: ServerlessBotFrameworkStackProps ) { super(scope, id, props); const botName = new CfnParameter(this, 'BotName', { type: 'String', description: "Define the bot name. Allows a minimum 1 character and maximum of 20. This value is used when it will answer about it's name, for example Jao.", default: 'Joe', minLength: 1, maxLength: 20, }); const botLanguage = new CfnParameter(this, 'BotLanguage', { type: 'String', description: 'Choose the language that this bot will understand and comunicate.', default: 'English', allowedValues: [ 'English', 'Spanish', 'French', 'Italian', 'German', ], }); const botGender = new CfnParameter(this, 'BotGender', { type: 'String', description: 'Choose the bot voice gender.', allowedValues: ['Male', 'Female'], }); const adminUserName = new CfnParameter(this, 'AdminUserName', { type: 'String', description: 'The admin username to access the Serverless Bot Framework.', minLength: 4, maxLength: 20, allowedPattern: '[a-zA-Z0-9-]+', constraintDescription: 'The username must be a minimum of 4 characters, maximum of 20 and cannot include spaces.', }); const adminEmail = new CfnParameter(this, 'AdminEmail', { type: 'String', description: 'Admin user email address to access the Serverless Bot Framework.', minLength: 5, maxLength: 50, allowedPattern: '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$', constraintDescription: 'Admin email must be a valid email address.', }); const childDirected = new CfnParameter(this, 'ChildDirected', { type: 'String', description: "Is use of your bot subject to the Children's Online Privacy Protection Act (COPPA)", allowedValues: ['No', 'Yes'], }); const weatherAPIProvider = new CfnParameter(this, 'WeatherAPIProvider', { type: 'String', description: 'Choice of weather api source or a random weather generator.', default: 'Random Weather Generator', allowedValues: ['Random Weather Generator', 'AccuWeather', 'OpenWeather'], }); const weatherAPIKey = new CfnParameter(this, 'WeatherAPIKey', { type: 'String', description: 'API key for weather API (Optional). Not required for Random Weather Generator.', default: '', minLength: 0, maxLength: 64, allowedPattern: '[a-zA-Z0-9]*', noEcho: true, constraintDescription: 'The weather API Key must be a maximum of 64 characters (letters/numbers) and cannot include spaces.', }); /** Create Solution Mapping */ const solutionMapping = new CfnMapping(this, 'Solution', { mapping: { Data: { ID: 'SO0027', Version: '%%VERSION%%', SendAnonymousUsageData: 'Yes', }, }, }); /** Create Condition for WeatherAPIChosen*/ const weatherAPIChosen = new CfnCondition(this, 'WeatherAPIChosen', { expression: Fn.conditionNot( Fn.conditionEquals( weatherAPIProvider.valueAsString, 'Random Weather Generator' ) ), }); /** Create AnonymousDatatoAWS Condition */ const metricsCondition = new CfnCondition(this, 'AnonymousDatatoAWS', { expression: Fn.conditionEquals( solutionMapping.findInMap('Data', 'SendAnonymousUsageData'), 'Yes' ), }); /** Generate assethash for the WebClinetPackage used to deploy the static website */ const webPackageAsset = new Asset(this, 'WebPackage', { path: '../samples/webclient/build', }); /** Create a location for the Webclient package */ const webClientPackageLocation = { S3Bucket: `%%BUCKET_NAME%%-${Aws.REGION}`, S3Key: `%%SOLUTION_NAME%%/%%VERSION%%/asset${webPackageAsset.assetHash}.zip`, }; /** Create SolutionHelper */ new SolutionHelper(this, 'SolutionHelper', { solutionId: solutionMapping.findInMap('Data', 'ID'), solutionVersion: solutionMapping.findInMap('Data', 'Version'), sendAnonymousDataCondition: metricsCondition, botName: botName.valueAsString, botGender: botGender.valueAsString, botLanguage: botLanguage.valueAsString, }); /** Create LexLambda => DynamoDB Table Integrations */ const lexLambdaDynamoDBTables = new LexLambdaDynamoDBTable( this, 'LexLambdaDynamoDB', { lexLambdaProps: { description: 'Serverless-bot-framework Sample lambda-lex integration functionalities', runtime: Runtime.PYTHON_3_8, code: Code.fromAsset('../samples/lex-lambdas'), handler: 'dispatcher.lambda_handler', timeout: Duration.minutes(5), environment: { childDirected: childDirected.valueAsString, } }, } ); /** Pass in lexLambda as OrderPizzaLambda and create OrderPizza DynamoDB Tables */ new OrderPizzaLambdaDynamoDBTables(this, 'OrderPizzaLambdaDynamoDB', { orderPizzaLambda: lexLambdaDynamoDBTables.lexLambda }); /** Lex Custom Resource */ const lexCustomResource = new LexCustomResource(this, 'LexCustomResrouce', { botName: botName.valueAsString, botLanguage: botLanguage.valueAsString, childDirected: childDirected.valueAsString, lexLambdaARN: lexLambdaDynamoDBTables.lexLambda.functionArn, }); /** Create CoreLambda */ const coreLambdaConstruct = new CoreLambda( this, 'coreLambda', { lambdaFunctionProps: { description: 'Serverless-bot-framework Core lambda', runtime: Runtime.NODEJS_12_X, code: Code.fromAsset('../services/core'), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 1024, environment: { botName: botName.valueAsString, botId: lexCustomResource.BotId, botAliasId: lexCustomResource.BotAliasId, botGender: botGender.valueAsString, botLanguage: botLanguage.valueAsString, forceCacheUpdate: 'false', }, }, } ); /** Create PollyLambda to Polly Service Integartion */ const lambdaToPolly = new LambdaToPolly(this, 'PollyLambdaToPolly', { lambdaFunctionProps: { description: 'Serverless-bot-framework Polly lambda', runtime: Runtime.NODEJS_12_X, code: Code.fromAsset('../services/polly-service'), handler: 'index.handler', timeout: Duration.minutes(5), memorySize: 128, }, }); /** Create CloudFront => StaticWebsite Integration */ const cloudfrontStaticWebsite = new CloudfrontStaticWebsite( this, 'CloudfrontStaticWebsite' ); /** Create Cognito=>ApiGateway=>CoreLambda/PollyLambda Integrations */ const cognitoApiCorePollyLambdas = new CognitoApiLambda(this, 'BotApi', { coreLambda: coreLambdaConstruct.coreLambda, pollyLambda: lambdaToPolly.pollyLambda, adminUserName: adminUserName.valueAsString, adminEmail: adminEmail.valueAsString, webClientDomainName: cloudfrontStaticWebsite.domainName, }); /** Create Weather Forecast's WriteAPIKey CustomResource => SSM Integration */ new WriteApiKeyCustomResource(this, 'WriteAPIKey', { weatherAPIKey: weatherAPIKey.valueAsString, weatherAPIChosen: weatherAPIChosen, }); /** Pass in lexLambda as weather forecast lambda and Create WeatherForecast => SSM Integration */ new WeatherForecastToSSM(this, 'WeatherForecastLambda', { weatherAPIProvider: weatherAPIProvider.valueAsString, weatherAPIChosen: weatherAPIChosen, weatherForecastLambda: lexLambdaDynamoDBTables.lexLambda }); const botApi = cognitoApiCorePollyLambdas.botApi; /** Create webClientPackageUrl */ const webClientPackageUrl = `https://s3.${Aws.REGION}.amazonaws.com/${webClientPackageLocation.S3Bucket}/${webClientPackageLocation.S3Key}`; /** Create CustomResource */ new WebClientCustomResource(this, 'WebClientCustomResource', { botApiUrl: `https://${botApi.restApiId}.execute-api.${Aws.REGION}.amazonaws.com/${botApi.deploymentStage.stageName}/`, botApiStageName: botApi.deploymentStage.stageName, botApiId: botApi.restApiId, botName: botName.valueAsString, botGender: botGender.valueAsString, botLanguage: botLanguage.valueAsString, cognitoIdentityPool: cognitoApiCorePollyLambdas.botCognitoIdentityPool.ref, cognitoUserPoolId: cognitoApiCorePollyLambdas.botCognitoUserPool.userPoolId, cognitoUserPoolClientId: cognitoApiCorePollyLambdas.botCognitoUserPoolClient.userPoolClientId, sampleWebClientBucketName: cloudfrontStaticWebsite.bucketName, sampleWebclientPackage: webClientPackageUrl, }); /** Create Template Interface */ this.templateOptions.metadata = { 'AWS::CloudFormation::Interface': { ParameterGroups: [ { Label: { default: 'Bot Settings' }, Parameters: [ botName.logicalId, botLanguage.logicalId, botGender.logicalId, ], }, { Label: { default: 'Sample web app' }, Parameters: [adminUserName.logicalId, adminEmail.logicalId], }, { Label: { default: 'Amazon Lex related parameters' }, Parameters: [childDirected.logicalId], }, { Label: { default: 'Weather API parameters' }, Parameters: [weatherAPIProvider.logicalId, weatherAPIKey.logicalId], }, ], ParameterLabels: { [botName.logicalId]: { default: 'Name' }, [botLanguage.logicalId]: { default: 'Language' }, [botGender.logicalId]: { default: 'Gender' }, [weatherAPIProvider.logicalId]: { default: 'Weather API provider' }, [weatherAPIKey.logicalId]: { default: 'Weather API Key (Empty if no API provider)', }, }, }, }; /** Stack Outputs */ new CfnOutput(this, 'ApiEndpoint', { exportName: 'ApiEndpoint', value: `https://${botApi.restApiId}.execute-api.${Aws.REGION}.amazonaws.com/${botApi.deploymentStage.stageName}/`, description: 'API URL for customers build their own clients consumers.', }); new CfnOutput(this, 'WebClientDomainName', { exportName: 'WebClientDomainName', value: cloudfrontStaticWebsite.domainName, description: 'Sample web client domain name.', }); new CfnOutput(this, 'WebClientBucket', { exportName: 'WebClientBucket', value: cloudfrontStaticWebsite.bucketName, description: 'Sample web client bucket name.', }); new CfnOutput(this, 'CognitoUserPoolId', { exportName: 'CognitoUserPoolId', value: cognitoApiCorePollyLambdas.botCognitoUserPool.userPoolId, description: 'Cognito User Pool ID.', }); new CfnOutput(this, 'CognitoUserPoolClientId', { exportName: 'CognitoUserPoolClientId', value: cognitoApiCorePollyLambdas.botCognitoUserPoolClient.userPoolClientId, description: 'Client ID for Cognito User Pool.', }); new CfnOutput(this, 'CognitoIdentityPool', { exportName: 'CognitoIdentityPool', value: cognitoApiCorePollyLambdas.botCognitoIdentityPool.ref, description: 'Cognito Identity Pool ID.', }); } }
the_stack
import fs from 'fs' import assert from 'assert' import net from 'net' import Ca from '../../src/service/caService' import config from '../../src/config' import { CaEnrollCommandTypeEnum, CaRegisterTypeEnum } from '../../src/model/type/caService.type' describe('CA service:', function () { this.timeout(10000) let caService: Ca const rcaArgv = { basic: { caName: 'rca.cathaybc.com', port: 7054, adminUser: 'admin', adminPass: 'adminpw', }, crypto: { tlsCertFile: '', tlsKeyFile: '', caCertFile: '', caKeyFile: '' }, signing: { defaultExpiry: '8760h', profilesCaExpiry: '43800h', profilesTlsExpiry: '8760h', }, csr: { cn: 'rca.cathaybc.com', hosts: 'rca.cathaybc.com', expiry: '87600h', pathlength: 1, }, intermediate: { parentserverUrl: 'https://<id>:<secret>@hostname', parentserverCn: '', enrollmentHost: '', }, upstreamEnabled: false, } const icaArgv = { basic: { caName: 'ica.org0.cathaybc.com', port: 7154, adminUser: 'admin', adminPass: 'adminpw', }, crypto: { tlsCertFile: '', tlsKeyFile: '', caCertFile: '', caKeyFile: '' }, signing: { defaultExpiry: '8760h', profilesCaExpiry: '43800h', profilesTlsExpiry: '8760h', }, csr: { cn: '', hosts: '', expiry: '131400h', pathlength: 0 }, intermediate: { parentserverUrl: 'https://ica.org0.cathaybc.com:org0icapw@rca.cathaybc.com:7054', parentserverCn: 'rca.cathaybc.com', enrollmentHost: 'ica.org0.cathaybc.com', }, upstreamEnabled: true, } const enrollRcaClientArgv = { upstream: 'rca.cathaybc.com', upstreamPort: 7054, clientId: 'admin', clientSecret: 'adminpw', type: CaEnrollCommandTypeEnum.client, role: 'rca', orgHostname: 'rca.cathaybc.com', } const enrollOrdererClientArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'admin', clientSecret: 'adminpw', type: CaEnrollCommandTypeEnum.client, role: 'orderer', orgHostname: 'org0orderer.bdk.example.com', } const enrollOrdererOrgArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'Admin@org0orderer.bdk.example.com', clientSecret: 'adminpw', type: CaEnrollCommandTypeEnum.user, role: 'orderer', orgHostname: 'org0orderer.bdk.example.com', } const enrollOrderer0Argv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'orderer0.org0orderer.bdk.example.com', clientSecret: 'org0ordererpw', type: CaEnrollCommandTypeEnum.orderer, role: 'orderer', orgHostname: 'org0orderer.bdk.example.com', } const enrollPeerClientArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'admin', clientSecret: 'adminpw', type: CaEnrollCommandTypeEnum.client, role: 'peer', orgHostname: 'org0.bdk.example.com', } const enrollPeerOrgArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'Admin@org0.bdk.example.com', clientSecret: 'adminpw', type: CaEnrollCommandTypeEnum.user, role: 'peer', orgHostname: 'org0.bdk.example.com', } const enrollPeer0Argv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'peer0.org0.bdk.example.com', clientSecret: 'org0peerpw', type: CaEnrollCommandTypeEnum.peer, role: 'peer', orgHostname: 'org0.bdk.example.com', } const registerIcaArgv = { upstream: 'rca.cathaybc.com', upstreamPort: 7054, clientId: 'ica.org0.cathaybc.com', clientSecret: 'org0icapw', type: CaRegisterTypeEnum.ica, admin: 'admin', } const registerOrdererOrgArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'Admin@org0orderer.bdk.example.com', clientSecret: 'adminpw', type: CaRegisterTypeEnum.admin, admin: 'admin', } const registerOrderer0Argv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'orderer0.org0orderer.bdk.example.com', clientSecret: 'org0ordererpw', type: CaRegisterTypeEnum.orderer, admin: 'admin', } const registerPeerOrgArgv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'Admin@org0.bdk.example.com', clientSecret: 'adminpw', type: CaRegisterTypeEnum.admin, admin: 'admin', } const registerPeer0Argv = { upstream: 'ica.org0.cathaybc.com', upstreamPort: 7154, clientId: 'peer0.org0.bdk.example.com', clientSecret: 'org0peerpw', type: CaRegisterTypeEnum.peer, admin: 'admin', } before(() => { caService = new Ca(config) }) describe('enroll && register ica', function () { after(() => { fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('up & down', (done) => { caService.up(rcaArgv).then(() => { const socket = net.connect(rcaArgv.basic.port, '127.0.0.1', () => { caService.down({ caName: rcaArgv.basic.caName }) .then(() => { // TODO check container done() }) .catch((err) => { assert.fail(`ca down error: ${err.message}`) }) }) socket.on('error', (err) => { assert.fail(`ca connect test error: ${err.message}`) }) }).catch((err) => { assert.fail(`ca up error: ${err.message}`) }) }) }) describe('enroll && register ica', function () { before((done) => { caService.up(rcaArgv).then(() => { const socket = net.connect(rcaArgv.basic.port, '127.0.0.1', () => { done() }) socket.on('error', (err) => { assert.fail(`rca connect test error: ${err.message}`) }) }).catch((err) => { assert.fail(`rca up error: ${err.message}`) }) }) after((done) => { caService.down({ caName: rcaArgv.basic.caName }) .then(() => { fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) done() }).catch((err) => { assert.fail(`rca down error: ${err.message}`) }) }) it('enroll client', async () => { await caService.enroll(enrollRcaClientArgv) const caPath = `${config.infraConfig.bdkPath}/${config.networkName}/ca` // folder assert.strictEqual(fs.existsSync(`${caPath}`), true) // yaml assert.strictEqual(fs.existsSync(`${caPath}/${rcaArgv.basic.adminUser}@${rcaArgv.basic.caName}/fabric-ca-client-config.yaml`), true) // ca assert.strictEqual(fs.existsSync(`${caPath}/${rcaArgv.basic.caName}/crypto/ca-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${caPath}/${rcaArgv.basic.caName}/crypto/tls-cert.pem`), true) }) it('register ica', async () => { await caService.register(registerIcaArgv) }) }) describe('enroll && register org', function () { this.timeout(60000) before((done) => { caService.up(rcaArgv).then(() => { const socket = net.connect(rcaArgv.basic.port, '127.0.0.1', () => { caService.enroll(enrollRcaClientArgv).then(() => { caService.register(registerIcaArgv).then(() => { caService.up(icaArgv).then(() => { const socket = net.connect(icaArgv.basic.port, '127.0.0.1', () => { done() }) socket.on('error', (err) => { assert.fail(`ica connect test error: ${err.message}`) }) }).catch((err) => { assert.fail(`ica up error: ${err.message}`) }) }).catch((err) => { assert.fail(`rca register ica error: ${err.message}`) }) }).catch((err) => { assert.fail(`rca enroll client error: ${err.message}`) }) }) socket.on('error', (err) => { assert.fail(`rca connect test error: ${err.message}`) }) }).catch((err) => { assert.fail(`rca up error: ${err.message}`) }) }) after((done) => { caService.down({ caName: rcaArgv.basic.caName }).then(() => { caService.down({ caName: icaArgv.basic.caName }).then(() => { fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) done() }).catch((err) => { assert.fail(`ica down error: ${err.message}`) }) }).catch((err) => { assert.fail(`rca down error: ${err.message}`) }) }) it('enroll && register orderer', async () => { await caService.enroll(enrollOrdererClientArgv) await caService.register(registerOrdererOrgArgv) await caService.enroll(enrollOrdererOrgArgv) await caService.register(registerOrderer0Argv) await caService.enroll(enrollOrderer0Argv) const caPath = `${config.infraConfig.bdkPath}/${config.networkName}/ca` const ordererOrgPath = `${config.infraConfig.bdkPath}/${config.networkName}/ordererOrganizations/${enrollOrdererOrgArgv.orgHostname}` // folder assert.strictEqual(fs.existsSync(`${caPath}`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}`), true) // ca assert.strictEqual(fs.existsSync(`${caPath}/${enrollOrdererOrgArgv.clientId}@${enrollOrdererOrgArgv.upstream}/user/cacerts`), true) assert.strictEqual(fs.existsSync(`${caPath}/${enrollOrderer0Argv.clientId}@${enrollOrderer0Argv.upstream}/msp/cacerts`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/ca/ca.${enrollOrdererOrgArgv.orgHostname}-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${caPath}/${enrollOrderer0Argv.clientId}@${enrollOrderer0Argv.upstream}/tls/tlsintermediatecerts`), true) assert.strictEqual(fs.existsSync(`${caPath}/${enrollOrderer0Argv.clientId}@${enrollOrderer0Argv.upstream}/tls/tlscacerts`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/users/Admin@${enrollOrdererOrgArgv.orgHostname}/msp/intermediatecerts`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/orderers/${enrollOrderer0Argv.clientId}/tls/tlscacerts`), true) // yaml assert.strictEqual(fs.existsSync(`${caPath}/${enrollOrderer0Argv.clientId}@${enrollOrderer0Argv.upstream}/fabric-ca-client-config.yaml`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/orderers/${enrollOrderer0Argv.clientId}/fabric-ca-client-config.yaml`), true) }) it('enroll && register peer', async () => { await caService.enroll(enrollPeerClientArgv) await caService.register(registerPeerOrgArgv) await caService.enroll(enrollPeerOrgArgv) await caService.register(registerPeer0Argv) await caService.enroll(enrollPeer0Argv) const caPath = `${config.infraConfig.bdkPath}/${config.networkName}/ca` const peerOrgPath = `${config.infraConfig.bdkPath}/${config.networkName}/peerOrganizations/${enrollPeerOrgArgv.orgHostname}` // folder assert.strictEqual(fs.existsSync(`${caPath}`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}`), true) // ca assert.strictEqual(fs.existsSync(`${caPath}/${enrollPeerOrgArgv.clientId}@${enrollPeerOrgArgv.upstream}/user/cacerts`), true) assert.strictEqual(fs.existsSync(`${caPath}/${enrollPeer0Argv.clientId}@${enrollPeer0Argv.upstream}/msp/cacerts`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/ca/ca.${enrollPeerOrgArgv.orgHostname}-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${caPath}/${enrollPeer0Argv.clientId}@${enrollPeer0Argv.upstream}/tls/tlsintermediatecerts`), true) assert.strictEqual(fs.existsSync(`${caPath}/${enrollPeer0Argv.clientId}@${enrollPeer0Argv.upstream}/tls/tlscacerts`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${enrollPeerOrgArgv.orgHostname}/msp/intermediatecerts`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/peers/${enrollPeer0Argv.clientId}/tls/tlscacerts`), true) // yaml assert.strictEqual(fs.existsSync(`${caPath}/${enrollPeer0Argv.clientId}@${enrollPeer0Argv.upstream}/fabric-ca-client-config.yaml`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/peers/${enrollPeer0Argv.clientId}/fabric-ca-client-config.yaml`), true) }) }) })
the_stack
import { MessengerContext, MessengerEvent } from 'bottender'; import FacebookClient from '../FacebookClient'; import FacebookConnector from '../FacebookConnector'; import FacebookEvent from '../FacebookEvent'; jest.mock('warning'); const ACCESS_TOKEN = 'FAKE_TOKEN'; const APP_SECRET = 'FAKE_SECRET'; const VERIFY_TOKEN = 'VERIFY_TOKEN'; const request = { body: { object: 'page', entry: [ { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', seq: 339979, text: 'text', }, }, ], }, ], }, }; const differentPagebatchRequest = { body: { object: 'page', entry: [ { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', seq: 339979, text: 'test 1', }, }, ], }, { id: '189538289069256', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '189538289069256', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a656', seq: 339979, text: 'test 2', }, }, ], }, ], }, }; const samePageBatchRequest = { body: { object: 'page', entry: [ { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a654', seq: 339979, text: 'test 1', }, }, ], }, { id: '1895382890692545', time: 1486464322257, messaging: [ { sender: { id: '1412611362105802', }, recipient: { id: '1895382890692545', }, timestamp: 1486464322190, message: { mid: 'mid.1486464322190:cb04e5a656', seq: 339979, text: 'test 2', }, }, ], }, ], }, }; const standbyRequest = { body: { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, standby: [ { sender: { id: '<USER_ID>', }, recipient: { id: '<PAGE_ID>', }, // FIXME: standby is still beta // https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/standby /* ... */ }, ], }, ], }, }; const commentAddRequest = { body: { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, changes: [ { field: 'feed', value: { from: { id: '139560936744123', name: 'user', }, item: 'comment', commentId: '139560936744456_139620233405726', postId: '137542570280222_139560936744456', verb: 'add', parentId: '139560936744456_139562213411528', createdTime: 1511951015, message: 'Good', }, }, ], }, { id: '<OTHER_PAGE_ID>', time: 1458692752478, changes: [ { field: 'feed', value: { from: { id: '139560936744123', name: 'user', }, item: 'comment', commentId: '139560936744456_139620233405726', postId: '137542570280222_139560936744456', verb: 'add', parentId: '139560936744456_139562213411528', createdTime: 1511951015, message: 'Good', }, }, ], }, ], }, }; function setup({ accessToken = ACCESS_TOKEN, appSecret = APP_SECRET, mapPageToAccessToken, verifyToken = VERIFY_TOKEN, }: { accessToken?: string; appSecret?: string; mapPageToAccessToken?: (pageId: string) => Promise<string>; verifyToken?: string; } = {}) { const mockGraphAPIClient = { getUserProfile: jest.fn(), }; FacebookClient.connect = jest.fn(); FacebookClient.connect.mockReturnValue(mockGraphAPIClient); return { mockGraphAPIClient, connector: new FacebookConnector({ accessToken, appSecret, mapPageToAccessToken, verifyToken, }), }; } describe('#mapRequestToEvents', () => { it('should map request to FacebookEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(request.body); expect(events).toHaveLength(1); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1895382890692545'); }); it('should work with batch entry from same page', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(samePageBatchRequest.body); expect(events).toHaveLength(2); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1895382890692545'); expect(events[1]).toBeInstanceOf(MessengerEvent); expect(events[1].pageId).toBe('1895382890692545'); }); it('should work with batch entry from different page', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(differentPagebatchRequest.body); expect(events).toHaveLength(2); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('1895382890692545'); expect(events[1]).toBeInstanceOf(MessengerEvent); expect(events[1].pageId).toBe('189538289069256'); }); it('should map request to standby FacebookEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(standbyRequest.body); expect(events).toHaveLength(1); expect(events[0]).toBeInstanceOf(MessengerEvent); expect(events[0].pageId).toBe('<PAGE_ID>'); expect(events[0].isStandby).toBe(true); }); it('should map request to changes FacebookEvents', () => { const { connector } = setup(); const events = connector.mapRequestToEvents(commentAddRequest.body); expect(events).toHaveLength(2); expect(events[0]).toBeInstanceOf(FacebookEvent); expect(events[0].pageId).toBe('<PAGE_ID>'); expect(events[1]).toBeInstanceOf(FacebookEvent); expect(events[1].pageId).toBe('<OTHER_PAGE_ID>'); }); it('should be filtered if body is not messaging or standby', () => { const otherRequest = { body: { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, other: [ { sender: { id: '<USER_ID>', }, recipient: { id: '<PAGE_ID>', }, }, ], }, ], }, }; const { connector } = setup(); const events = connector.mapRequestToEvents(otherRequest.body); expect(events).toHaveLength(0); }); it('should pass pageId when the body.object is `page`', () => { const { connector } = setup(); const commentAddRequestByPage = { body: { object: 'page', entry: [ { id: '<PAGE_ID>', time: 1458692752478, changes: [ { field: 'feed', value: { from: { id: '<PAGE_ID>', name: 'user', }, item: 'comment', commentId: '139560936744456_139620233405726', postId: '137542570280222_139560936744456', verb: 'add', parentId: '139560936744456_139562213411528', createdTime: 1511951015, message: 'Good', }, }, ], }, ], }, }; const events = connector.mapRequestToEvents(commentAddRequestByPage.body); expect(events[0].pageId).toBe('<PAGE_ID>'); expect(events[0].isSentByPage).toBe(true); }); }); describe('#createContext', () => { it('should create MessengerContext', async () => { const { connector } = setup(); const event = { rawEvent: { recipient: { id: 'anyPageId', }, }, }; const session = {}; const context = await connector.createContext({ event, session, }); expect(context).toBeDefined(); expect(context).toBeInstanceOf(MessengerContext); }); it('should create MessengerContext and has customAccessToken', async () => { const mapPageToAccessToken = jest.fn(() => Promise.resolve('anyToken')); const { connector } = setup({ mapPageToAccessToken }); const event = { pageId: 'anyPageId', }; const session = {}; const context = await connector.createContext({ event, session, }); expect(context).toBeDefined(); expect(context.accessToken).toBe('anyToken'); }); });
the_stack
import { SpanKind, Span, SpanStatusCode, Context, propagation, Link, trace, context, diag, ROOT_CONTEXT, } from '@opentelemetry/api'; import { SemanticAttributes, MessagingOperationValues, MessagingDestinationKindValues, } from '@opentelemetry/semantic-conventions'; import * as kafkaJs from 'kafkajs'; import { Producer, ProducerBatch, RecordMetadata, Message, ProducerRecord, ConsumerRunConfig, EachMessagePayload, KafkaMessage, EachBatchPayload, Consumer, } from 'kafkajs'; import { KafkaJsInstrumentationConfig } from './types'; import { VERSION } from './version'; import { bufferTextMapGetter } from './propagtor'; import { InstrumentationBase, InstrumentationModuleDefinition, InstrumentationNodeModuleDefinition, safeExecuteInTheMiddle, isWrapped, } from '@opentelemetry/instrumentation'; export class KafkaJsInstrumentation extends InstrumentationBase<typeof kafkaJs> { static readonly component = 'kafkajs'; protected override _config!: KafkaJsInstrumentationConfig; private moduleVersion: string; constructor(config: KafkaJsInstrumentationConfig = {}) { super('opentelemetry-instrumentation-kafkajs', VERSION, Object.assign({}, config)); } override setConfig(config: KafkaJsInstrumentationConfig = {}) { this._config = Object.assign({}, config); } protected init(): InstrumentationModuleDefinition<typeof kafkaJs> { const module = new InstrumentationNodeModuleDefinition<typeof kafkaJs>( KafkaJsInstrumentation.component, ['*'], this.patch.bind(this), this.unpatch.bind(this) ); return module; } protected patch(moduleExports: typeof kafkaJs, moduleVersion: string) { diag.debug('kafkajs instrumentation: applying patch'); this.moduleVersion = moduleVersion; this.unpatch(moduleExports); this._wrap(moduleExports?.Kafka?.prototype, 'producer', this._getProducerPatch.bind(this)); this._wrap(moduleExports?.Kafka?.prototype, 'consumer', this._getConsumerPatch.bind(this)); return moduleExports; } protected unpatch(moduleExports: typeof kafkaJs) { diag.debug('kafkajs instrumentation: un-patching'); if (isWrapped(moduleExports?.Kafka?.prototype.producer)) { this._unwrap(moduleExports.Kafka.prototype, 'producer'); } if (isWrapped(moduleExports?.Kafka?.prototype.consumer)) { this._unwrap(moduleExports.Kafka.prototype, 'consumer'); } } private _getConsumerPatch(original: (...args: unknown[]) => Producer) { const self = this; return function (...args: unknown[]): Consumer { const newConsumer: Consumer = original.apply(this, arguments); if (isWrapped(newConsumer.run)) { self._unwrap(newConsumer, 'run'); } self._wrap(newConsumer, 'run', self._getConsumerRunPatch.bind(self)); return newConsumer; }; } private _getProducerPatch(original: (...args: unknown[]) => Producer) { const self = this; return function (...args: unknown[]): Producer { const newProducer: Producer = original.apply(this, arguments); if (isWrapped(newProducer.sendBatch)) { self._unwrap(newProducer, 'sendBatch'); } self._wrap(newProducer, 'sendBatch', self._getProducerSendBatchPatch.bind(self)); if (isWrapped(newProducer.send)) { self._unwrap(newProducer, 'send'); } self._wrap(newProducer, 'send', self._getProducerSendPatch.bind(self)); return newProducer; }; } private _getConsumerRunPatch(original: (...args: unknown[]) => Producer) { const self = this; return function (config?: ConsumerRunConfig): Promise<void> { if (config?.eachMessage) { if (isWrapped(config.eachMessage)) { self._unwrap(config, 'eachMessage'); } self._wrap(config, 'eachMessage', self._getConsumerEachMessagePatch.bind(self)); } if (config?.eachBatch) { if (isWrapped(config.eachBatch)) { self._unwrap(config, 'eachBatch'); } self._wrap(config, 'eachBatch', self._getConsumerEachBatchPatch.bind(self)); } return original.call(this, config); }; } private _getConsumerEachMessagePatch(original: (...args: unknown[]) => Promise<void>) { const self = this; return function (payload: EachMessagePayload): Promise<void> { const propagatedContext: Context = propagation.extract( ROOT_CONTEXT, payload.message.headers, bufferTextMapGetter ); const span = self._startConsumerSpan( payload.topic, payload.message, MessagingOperationValues.PROCESS, propagatedContext ); const eachMessagePromise = context.with(trace.setSpan(context.active(), span), () => { return original.apply(this, arguments); }); return self._endSpansOnPromise([span], eachMessagePromise); }; } private _getConsumerEachBatchPatch(original: (...args: unknown[]) => Promise<void>) { const self = this; return function (payload: EachBatchPayload): Promise<void> { // https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/messaging.md#topic-with-multiple-consumers const receivingSpan = self._startConsumerSpan( payload.batch.topic, undefined, MessagingOperationValues.RECEIVE, ROOT_CONTEXT ); return context.with(trace.setSpan(context.active(), receivingSpan), () => { const spans = payload.batch.messages.map((message: KafkaMessage) => { const propagatedContext: Context = propagation.extract( ROOT_CONTEXT, message.headers, bufferTextMapGetter ); const spanContext = trace.getSpan(propagatedContext)?.spanContext(); let origSpanLink: Link; if (spanContext) { origSpanLink = { context: spanContext, }; } return self._startConsumerSpan( payload.batch.topic, message, MessagingOperationValues.PROCESS, undefined, origSpanLink ); }); const batchMessagePromise: Promise<void> = original.apply(this, arguments); spans.unshift(receivingSpan); return self._endSpansOnPromise(spans, batchMessagePromise); }); }; } private _getProducerSendBatchPatch(original: (batch: ProducerBatch) => Promise<RecordMetadata[]>) { const self = this; return function (batch: ProducerBatch): Promise<RecordMetadata[]> { const spans: Span[] = batch.topicMessages .map((topicMessage) => topicMessage.messages.map((message) => self._startProducerSpan(topicMessage.topic, message)) ) .reduce((acc, val) => acc.concat(val), []); const origSendResult: Promise<RecordMetadata[]> = original.apply(this, arguments); return self._endSpansOnPromise(spans, origSendResult); }; } private _getProducerSendPatch(original: (record: ProducerRecord) => Promise<RecordMetadata[]>) { const self = this; return function (record: ProducerRecord): Promise<RecordMetadata[]> { const spans: Span[] = record.messages.map((message) => { return self._startProducerSpan(record.topic, message); }); const origSendResult: Promise<RecordMetadata[]> = original.apply(this, arguments); return self._endSpansOnPromise(spans, origSendResult); }; } private _endSpansOnPromise<T>(spans: Span[], sendPromise: Promise<T>): Promise<T> { return Promise.resolve(sendPromise) .catch((reason) => { let errorMessage; if (typeof reason === 'string') errorMessage = reason; else if (typeof reason === 'object' && reason.hasOwnProperty('message')) errorMessage = reason.message; spans.forEach((span) => span.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage, }) ); throw reason; }) .finally(() => { spans.forEach((span) => span.end()); }); } private _startConsumerSpan(topic: string, message: KafkaMessage, operation: string, context: Context, link?: Link) { const span = this.tracer.startSpan( topic, { kind: SpanKind.CONSUMER, attributes: { [SemanticAttributes.MESSAGING_SYSTEM]: 'kafka', [SemanticAttributes.MESSAGING_DESTINATION]: topic, [SemanticAttributes.MESSAGING_DESTINATION_KIND]: MessagingDestinationKindValues.TOPIC, [SemanticAttributes.MESSAGING_OPERATION]: operation, }, links: link ? [link] : [], }, context ); if (this._config.moduleVersionAttributeName) { span.setAttribute(this._config.moduleVersionAttributeName, this.moduleVersion); } if (this._config?.consumerHook && message) { safeExecuteInTheMiddle( () => this._config.consumerHook!(span, topic, message), (e: Error) => { if (e) diag.error(`kafkajs instrumentation: consumerHook error`, e); }, true ); } return span; } private _startProducerSpan(topic: string, message: Message) { const span = this.tracer.startSpan(topic, { kind: SpanKind.PRODUCER, attributes: { [SemanticAttributes.MESSAGING_SYSTEM]: 'kafka', [SemanticAttributes.MESSAGING_DESTINATION]: topic, [SemanticAttributes.MESSAGING_DESTINATION_KIND]: MessagingDestinationKindValues.TOPIC, }, }); if (this._config.moduleVersionAttributeName) { span.setAttribute(this._config.moduleVersionAttributeName, this.moduleVersion); } message.headers = message.headers ?? {}; propagation.inject(trace.setSpan(context.active(), span), message.headers); if (this._config?.producerHook) { safeExecuteInTheMiddle( () => this._config.producerHook!(span, topic, message), (e: Error) => { if (e) diag.error(`kafkajs instrumentation: producerHook error`, e); }, true ); } return span; } }
the_stack
import { Agile, State, Observer, Collection, StateObserver, GroupObserver, } from '../../src'; import * as Utils from '../../src/utils'; import { LogMock } from '../helper/logMock'; describe('Utils Tests', () => { let dummyAgile: Agile; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); // @ts-ignore | Reset globalThis globalThis = {}; jest.clearAllMocks(); }); describe('extractObservers function tests', () => { // Observer 1 let dummyObserver: Observer; // Observer 2 let dummyObserver2: Observer; // State with one Observer let dummyStateObserver: StateObserver; let dummyState: State; // State with multiple Observer let dummyStateWithMultipleObserver: State; let dummyStateValueObserver: StateObserver; let dummyStateRandomObserver: StateObserver; // Collection let dummyCollection: Collection; let dummyDefaultGroupValueObserver: StateObserver; let dummyDefaultGroupOutputObserver: GroupObserver; beforeEach(() => { // Observer 1 dummyObserver = new Observer(dummyAgile); // Observer 2 dummyObserver2 = new Observer(dummyAgile); // State with one Observer dummyState = new State(dummyAgile, null); dummyStateObserver = new StateObserver(dummyState); dummyState.observers['value'] = dummyStateObserver; // State with multiple Observer dummyStateWithMultipleObserver = new State(dummyAgile, null); dummyStateValueObserver = new StateObserver(dummyState); dummyStateWithMultipleObserver.observers['value'] = dummyStateValueObserver; dummyStateRandomObserver = new StateObserver(dummyState); dummyStateWithMultipleObserver.observers['random'] = dummyStateRandomObserver; // Collection dummyCollection = new Collection(dummyAgile); const defaultGroup = dummyCollection.groups[dummyCollection.config.defaultGroupKey]; dummyDefaultGroupValueObserver = new StateObserver(defaultGroup); defaultGroup.observers['value'] = dummyDefaultGroupValueObserver; dummyDefaultGroupOutputObserver = new GroupObserver(defaultGroup); defaultGroup.observers['output'] = dummyDefaultGroupOutputObserver; }); it('should extract Observer from specified Instance', () => { const response = Utils.extractObservers(dummyState); expect(response).toStrictEqual({ value: dummyStateObserver }); }); it('should extract Observers from specified Instances', () => { const response = Utils.extractObservers([ // Observer 1 dummyObserver, // State with one Observer dummyState, undefined, {}, // State with multiple Observer dummyStateWithMultipleObserver, { observer: 'fake' }, // Collection dummyCollection, // Observer 2 { observer: dummyObserver2 }, ]); expect(response).toStrictEqual([ // Observer 1 { value: dummyObserver }, // State with one Observer { value: dummyStateObserver }, {}, {}, // State with multiple Observer { value: dummyStateValueObserver, random: dummyStateRandomObserver }, {}, // Collection { value: dummyDefaultGroupValueObserver, output: dummyDefaultGroupOutputObserver, }, // Observer 2 { value: dummyObserver2 }, ]); }); }); describe('extractRelevantObservers function tests', () => { // State with one Observer let dummyStateObserver: StateObserver; let dummyState: State; // State with multiple Observer let dummyStateWithMultipleObserver: State; let dummyStateValueObserver: StateObserver; let dummyStateRandomObserver: StateObserver; // Collection let dummyCollection: Collection; let dummyDefaultGroupValueObserver: StateObserver; let dummyDefaultGroupOutputObserver: GroupObserver; beforeEach(() => { // State with one Observer dummyState = new State(dummyAgile, null); dummyStateObserver = new StateObserver(dummyState); dummyState.observers['value'] = dummyStateObserver; // State with multiple Observer dummyStateWithMultipleObserver = new State(dummyAgile, null); dummyStateValueObserver = new StateObserver(dummyState); dummyStateWithMultipleObserver.observers['value'] = dummyStateValueObserver; dummyStateRandomObserver = new StateObserver(dummyState); dummyStateWithMultipleObserver.observers['random'] = dummyStateRandomObserver; // Collection dummyCollection = new Collection(dummyAgile); const defaultGroup = dummyCollection.groups[dummyCollection.config.defaultGroupKey]; dummyDefaultGroupValueObserver = new StateObserver(defaultGroup); defaultGroup.observers['value'] = dummyDefaultGroupValueObserver; dummyDefaultGroupOutputObserver = new GroupObserver(defaultGroup); defaultGroup.observers['output'] = dummyDefaultGroupOutputObserver; jest.spyOn(Utils, 'extractObservers'); }); it('should extract Observers at the specified observerType from the Instances (array shape)', () => { const response = Utils.extractRelevantObservers( [ dummyState, dummyStateWithMultipleObserver, undefined, dummyCollection, ], 'output' ); expect(response).toStrictEqual([ undefined, undefined, undefined, dummyDefaultGroupOutputObserver, ]); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyState); // expect(Utils.extractObservers).toHaveBeenCalledWith( // dummyStateWithMultipleObserver // ); // expect(Utils.extractObservers).toHaveBeenCalledWith(undefined); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyCollection); }); it('should extract the most relevant Observer from the Instances (array shape)', () => { const response = Utils.extractRelevantObservers([ dummyState, dummyStateWithMultipleObserver, undefined, dummyCollection, ]); expect(response).toStrictEqual([ dummyStateObserver, dummyStateValueObserver, undefined, dummyDefaultGroupOutputObserver, ]); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyState); // expect(Utils.extractObservers).toHaveBeenCalledWith( // dummyStateWithMultipleObserver // ); // expect(Utils.extractObservers).toHaveBeenCalledWith(undefined); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyCollection); }); it('should extract Observers at the specified observerType from the Instances (object shape)', () => { const response = Utils.extractRelevantObservers( { dummyState, dummyStateWithMultipleObserver, undefinedObserver: undefined, dummyCollection, }, 'output' ); expect(response).toStrictEqual({ dummyState: undefined, dummyStateWithMultipleObserver: undefined, undefinedObserver: undefined, dummyCollection: dummyDefaultGroupOutputObserver, }); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyState); // expect(Utils.extractObservers).toHaveBeenCalledWith( // dummyStateWithMultipleObserver // ); // expect(Utils.extractObservers).toHaveBeenCalledWith(undefined); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyCollection); }); it('should extract the most relevant Observer from the Instances (object shape)', () => { const response = Utils.extractRelevantObservers({ dummyState, dummyStateWithMultipleObserver, undefinedObserver: undefined, dummyCollection, }); expect(response).toStrictEqual({ dummyState: dummyStateObserver, dummyStateWithMultipleObserver: dummyStateValueObserver, undefinedObserver: undefined, dummyCollection: dummyDefaultGroupOutputObserver, }); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyState); // expect(Utils.extractObservers).toHaveBeenCalledWith( // dummyStateWithMultipleObserver // ); // expect(Utils.extractObservers).toHaveBeenCalledWith(undefined); // expect(Utils.extractObservers).toHaveBeenCalledWith(dummyCollection); }); }); describe('optionalRequire function tests', () => { beforeEach(() => { jest.resetModules(); }); it("should return null if to retrieve package doesn't exist (error = false)", () => { const response = Utils.optionalRequire('@notExisting/package', false); expect(response).toBeNull(); LogMock.hasNotLoggedCode('20:03:02', ['@notExisting/package']); }); it("should return null and print error if to retrieve package doesn't exist (error = true)", () => { const response = Utils.optionalRequire('@notExisting/package', true); expect(response).toBeNull(); LogMock.hasLoggedCode('20:03:02', ['@notExisting/package']); }); it('should return package if to retrieve package exists', () => { // Create fake package const notExistingPackage = 'hehe fake package'; jest.mock( '@notExisting/package', () => { return notExistingPackage; }, { virtual: true } ); const response = Utils.optionalRequire('@notExisting/package'); expect(response).toBe(notExistingPackage); LogMock.hasNotLoggedCode('20:03:02', ['@notExisting/package']); }); }); describe('globalBind function tests', () => { const dummyKey = 'myDummyKey'; beforeEach(() => { globalThis[dummyKey] = undefined; }); it('should bind Instance globally at the specified key (default config)', () => { Utils.globalBind(dummyKey, 'dummyInstance'); expect(globalThis[dummyKey]).toBe('dummyInstance'); }); it("shouldn't overwrite already globally bound Instance at the same key (default config)", () => { Utils.globalBind(dummyKey, 'I am first!'); Utils.globalBind(dummyKey, 'dummyInstance'); expect(globalThis[dummyKey]).toBe('I am first!'); }); it('should overwrite already globally bound Instance at the same key (overwrite = true)', () => { Utils.globalBind(dummyKey, 'I am first!'); Utils.globalBind(dummyKey, 'dummyInstance', true); expect(globalThis[dummyKey]).toBe('dummyInstance'); }); it('should print error if something went wrong during the bind process', () => { // @ts-ignore | Destroy globalThis globalThis = undefined; Utils.globalBind(dummyKey, 'dummyInstance'); LogMock.hasLoggedCode('20:03:01', [dummyKey]); }); }); describe('runsOnServer function tests', () => { it("should return 'false' if the current environment isn't a server", () => { global.window = { document: { createElement: 'isSet' as any, } as any, } as any; expect(Utils.runsOnServer()).toBeFalsy(); }); it("should return 'true' if the current environment is a server", () => { global.window = undefined as any; expect(Utils.runsOnServer()).toBeTruthy(); }); }); });
the_stack
import * as assert from 'assert'; import { before } from 'mocha'; import { EOL } from 'os'; // You can import and use all API from the 'vscode' module // as well as import your extension to test it import * as vscode from 'vscode'; import { PddlFormatProvider } from '../../formatting/PddlFormatProvider'; import { assertStrictEqualDecorated } from './testUtils'; let formatProvider: PddlFormatProvider; /* eslint-disable @typescript-eslint/no-use-before-define */ suite('Domain formatter Test Suite', () => { before(async () => { vscode.window.showInformationMessage('Start all tests.'); formatProvider = new PddlFormatProvider(); }); test('Does not modify well formatted text', async () => { // GIVEN const inputText = `(define)`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Removes white space before closing bracket', async () => { // GIVEN const inputText = `(define )`; const expectedText = `(define)`; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Removes extra white-space', async () => { // GIVEN const inputText = `(define (domain domain_name))`; const expectedText = [`(define (domain domain_name)`, `)`].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('does not modify comment', async () => { // GIVEN const inputText = [`(define`, `\t; comment`, `)`].join('\n'); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('does not modify flatten 2 consecutive comments', async () => { // GIVEN const inputText = [`(define`, `\t; comment1`, `\t; comment2`, `)`].join('\n'); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('Indents requirements', async () => { // GIVEN const inputText = `(define (domain domain_name) (:requirements :strips) )`; const expectedText = `(define (domain domain_name) (:requirements :strips) )`; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not indent individual requirements', async () => { // GIVEN const inputText = `(:requirements :strips :typing)`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not format formatted types', async () => { // GIVEN const inputText = [`(define`, ` (:types`, ` child11 child12`, ` )`, `)`].join(EOL); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Formats types', async () => { // GIVEN const inputText = `(define (:types child11 child12))`; const expectedText = [`(define`, ` (:types`, ` child11 child12`, ` )`, `)`].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Formats types with a comment', async () => { // GIVEN const inputText = [ `(define (:types child11`, `; comment1`, `child12))` ].join(EOL); const expectedText = [`(define`, ` (:types`, ` child11`, ` ; comment1`, ` child12`, ` )`, `)`].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Formats types with inheritance', async () => { // GIVEN const inputText = `(define (domain domain_name)(:types child11 child12 - parent1 child21 child22 - parent2))`; const expectedText = [`(define (domain domain_name)`, ` (:types`, ` child11 child12 - parent1`, ` child21 child22 - parent2`, ` )`, `)`].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Formats constants', async () => { // GIVEN const inputText = `(define (domain domain_name)(:constants object11 object12 - type1 object21 object22 - type2))`; const expectedText = [`(define (domain domain_name)`, ` (:constants`, ` object11 object12 - type1`, ` object21 object22 - type2`, ` )`, `)`].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Removes trailing whitespace (last line)', async () => { // GIVEN const inputText = `(define) `; const expectedText = `(define)`; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Removes trailing whitespace', async () => { // GIVEN const inputText = [`(define (domain)\t\t`, `)`].join('\n'); const expectedText = [`(define (domain)`, `)`].join('\n'); await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not break line in numeric expressions', async () => { // GIVEN const inputText = `(= (f1) (f2))`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Formats numeric expression that is already broken to multiple lines', async () => { // GIVEN const inputText = `(= \n(f1)\n (f2))`; const expectedText = `(=\n\t(f1)\n\t(f2))`; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('Does not break line in logical expressions (not)', async () => { // GIVEN const inputText = `(not (p1))`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not break line in logical expressions (and)', async () => { // GIVEN const inputText = `(and (p1) (p2))`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not break line in temporal (at start)', async () => { // GIVEN const inputText = `(at start (p1))`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: true, tabSize: 4 }); }); test('Does not break action keywords', async () => { // GIVEN const inputText = [`(:action a`, '\t:parameters (?p1 - param1)', ')' ].join('\n'); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('Does break line before action keywords', async () => { // GIVEN const inputText = [`(:action a`, '\t:parameters ()', '\t:precondition (and)', ')' ].join('\n'); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('keeps line break before comment line', async () => { // GIVEN const inputText = [`(:functions`, '\t(f1)', '\t; (f2)', ')' ].join('\n'); const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('removes excess empty lines', async () => { // GIVEN const inputText = [`(:init`, '\t(f1)', '\t', ' ', '\t(f2)', ')' ].join('\n'); const expectedText = [`(:init`, '\t(f1)', '', '\t(f2)', ')' ].join('\n'); await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('keeps short effects on one line', async () => { // GIVEN const inputText = `(assign (f1) 10)`; const expectedText = inputText; await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); test('splits long effect', async () => { // GIVEN const inputText = `(increase (ffffffffffffffffffffffffff1) (+ (gggggggggggggggggggg) 1))`; const expectedText = [ `(increase`, `\t(ffffffffffffffffffffffffff1)`, `\t(+ (gggggggggggggggggggg) 1))` ].join(EOL); await testFormatter(inputText, expectedText, { insertSpaces: false, tabSize: 4 }); }); }); async function testFormatter(initialText: string, expectedText: string, options: vscode.FormattingOptions): Promise<void> { // we do not want the extension to actually load (it takes too much time), so use a fake language const doc = await vscode.workspace.openTextDocument({ language: 'pddl-do-not-load-extension', content: initialText }); const editor = await vscode.window.showTextDocument(doc); // move the cursor into the text await vscode.commands.executeCommand("cursorMove", { to: 'right' }); const startSelectionBefore = editor.selection.start; // WHEN const edits = await formatProvider.provideDocumentFormattingEdits(doc, options, new vscode.CancellationTokenSource().token); if (edits) { await editor.edit(builder => reBuild(builder, edits)); } else { assert.fail('no edits returned'); } // THEN const startSelectionAfter = editor.selection.start; const textAfter = doc.getText(); assertStrictEqualDecorated(textAfter, expectedText, "document text should be formatted"); assert.deepStrictEqual(startSelectionAfter, startSelectionBefore, "cursor position should be the same"); } function reBuild(builder: vscode.TextEditorEdit, edits: vscode.TextEdit[]): void { edits.forEach(edit => builder.replace(edit.range, edit.newText)); }
the_stack
import { BN } from "bn.js"; import * as testUtils from "./helper/testUtils"; import { PausableTokenContract } from "./bindings/pausable_token"; import { RenExBalancesContract } from "./bindings/ren_ex_balances"; import { RenExBrokerVerifierContract } from "./bindings/ren_ex_broker_verifier"; import { RenExSettlementContract } from "./bindings/ren_ex_settlement"; import { StandardTokenContract } from "./bindings/standard_token"; import { VersionedContractContract } from "./bindings/versioned_contract"; const { RepublicToken, DGXToken, RenExBalances, RenExSettlement, VersionedContract, RenExBrokerVerifier, DisapprovingToken, TUSDToken, } = testUtils.contracts; contract("RenExBalances", function (accounts: string[]) { let renExBalances: RenExBalancesContract; let renExSettlement: RenExSettlementContract; let renExBrokerVerifier: RenExBrokerVerifierContract; let ETH: testUtils.BasicERC20; let REN: testUtils.BasicERC20; let TOKEN1: PausableTokenContract; let TOKEN2: StandardTokenContract; const broker = accounts[9]; before(async function () { ETH = testUtils.MockETH; REN = await RepublicToken.deployed(); TOKEN1 = await RepublicToken.new(); TOKEN2 = await DGXToken.new(); renExBalances = await RenExBalances.deployed(); renExSettlement = await RenExSettlement.deployed(); // Register broker renExBrokerVerifier = await RenExBrokerVerifier.deployed(); await renExBrokerVerifier.registerBroker(broker); }); it("can update Reward Vault address", async () => { const previousRewardVault = await renExBalances.rewardVaultContract(); // [CHECK] The function validates the new reward vault await renExBalances.updateRewardVaultContract(testUtils.NULL) .should.be.rejectedWith(null, /revert/); // [ACTION] Update the reward vault to another address await renExBalances.updateRewardVaultContract(renExBalances.address); // [CHECK] Verify the reward vault address has been updated (await renExBalances.rewardVaultContract()).should.equal(renExBalances.address); // [CHECK] Only the owner can update the reward vault await renExBalances.updateRewardVaultContract(previousRewardVault, { from: accounts[1] }) .should.be.rejectedWith(null, /revert/); // not owner // [RESET] Reset the reward vault to the previous address await renExBalances.updateRewardVaultContract(previousRewardVault); (await renExBalances.rewardVaultContract()).should.equal(previousRewardVault); }); it("can update Broker Verifier address", async () => { const previousBrokerVerifier = await renExBalances.brokerVerifierContract(); // [CHECK] The function validates the new broker verifier await renExBalances.updateBrokerVerifierContract(testUtils.NULL) .should.be.rejectedWith(null, /revert/); // [ACTION] Update the broker verifier to another address await renExBalances.updateBrokerVerifierContract(renExBalances.address); // [CHECK] Verify the broker verifier address has been updated (await renExBalances.brokerVerifierContract()).should.equal(renExBalances.address); // [CHECK] Only the owner can update the broker verifier await renExBalances.updateBrokerVerifierContract(previousBrokerVerifier, { from: accounts[1] }) .should.be.rejectedWith(null, /revert/); // not owner // [RESET] Reset the broker verifier to the previous address await renExBalances.updateBrokerVerifierContract(previousBrokerVerifier); (await renExBalances.brokerVerifierContract()).should.equal(previousBrokerVerifier); }); it("can update RenEx Settlement address", async () => { const previousSettlementContract = await renExBalances.settlementContract(); // [CHECK] The function validates the new settlement contract await renExBalances.updateRenExSettlementContract(testUtils.NULL) .should.be.rejectedWith(null, /revert/); // [ACTION] Update the settlement contract to another address await renExBalances.updateRenExSettlementContract(renExBalances.address); // [CHECK] Verify the settlement contract address has been updated (await renExBalances.settlementContract()).should.equal(renExBalances.address); // [CHECK] Only the owner can update the settlement contract await renExBalances.updateRenExSettlementContract(previousSettlementContract, { from: accounts[1] }) .should.be.rejectedWith(null, /revert/); // not owner // [RESET] Reset the settlement contract to the previous address await renExBalances.updateRenExSettlementContract(previousSettlementContract); (await renExBalances.settlementContract()).should.equal(previousSettlementContract); }); it("can hold tokens for a trader", async () => { const deposit1 = new BN("100000000000000000"); const deposit2 = new BN("50000000000000000"); // Get ERC20 balance for tokens const previous1 = new BN(await TOKEN1.balanceOf(accounts[0])); const previous2 = new BN(await TOKEN2.balanceOf(accounts[0])); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1, { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: accounts[0] }); await TOKEN2.approve(renExBalances.address, deposit2, { from: accounts[0] }); await renExBalances.deposit(TOKEN2.address, deposit2, { from: accounts[0] }); // Check that balance in renExBalances is updated (await renExBalances.traderBalances(accounts[0], TOKEN1.address)).should.bignumber.equal(deposit1); (await renExBalances.traderBalances(accounts[0], TOKEN2.address)).should.bignumber.equal(deposit2); // Check that the correct amount of tokens has been withdrawn (await TOKEN1.balanceOf(accounts[0])).should.bignumber.equal(previous1.sub(deposit1)); (await TOKEN2.balanceOf(accounts[0])).should.bignumber.equal(previous2.sub(deposit2)); // Withdraw let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }); sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN2.address); await renExBalances.withdraw(TOKEN2.address, deposit2, sig, { from: accounts[0] }); // Check that the tokens have been returned (await TOKEN1.balanceOf(accounts[0])).should.bignumber.equal(previous1); (await TOKEN2.balanceOf(accounts[0])).should.bignumber.equal(previous2); // Check that balance in renExBalances is zeroed (await renExBalances.traderBalances(accounts[0], TOKEN1.address)).should.bignumber.equal(0); (await renExBalances.traderBalances(accounts[0], TOKEN2.address)).should.bignumber.equal(0); }); it("can hold tokens for multiple traders", async () => { const deposit1 = new BN("100000000000000000"); const deposit2 = new BN("50000000000000000"); const TRADER_A = accounts[2]; const TRADER_B = accounts[3]; // Give accounts[1] some tokens await TOKEN1.transfer(TRADER_A, deposit1); await TOKEN1.transfer(TRADER_B, deposit2); // Get ERC20 balance for TOKEN1 and TOKEN2 const previous1 = new BN(await TOKEN1.balanceOf(TRADER_A)); const previous2 = new BN(await TOKEN1.balanceOf(TRADER_B)); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1, { from: TRADER_A }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: TRADER_A }); await TOKEN1.approve(renExBalances.address, deposit2, { from: TRADER_B }); await renExBalances.deposit(TOKEN1.address, deposit2, { from: TRADER_B }); // Check that balance in renExBalances is updated (await renExBalances.traderBalances(TRADER_A, TOKEN1.address)).should.bignumber.equal(deposit1); (await renExBalances.traderBalances(TRADER_B, TOKEN1.address)).should.bignumber.equal(deposit2); // Check that the correct amount of tokens has been withdrawn (await TOKEN1.balanceOf(TRADER_A)).should.bignumber.equal(previous1.sub(deposit1)); (await TOKEN1.balanceOf(TRADER_B)).should.bignumber.equal(previous2.sub(deposit2)); // Withdraw const sigA = await testUtils.signWithdrawal(renExBrokerVerifier, broker, TRADER_A, TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sigA, { from: TRADER_A }); const sigB = await testUtils.signWithdrawal(renExBrokerVerifier, broker, TRADER_B, TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit2, sigB, { from: TRADER_B }); // Check that the tokens have been returned (await TOKEN1.balanceOf(TRADER_A)).should.bignumber.equal(previous1); (await TOKEN1.balanceOf(TRADER_B)).should.bignumber.equal(previous2); }); it("throws for invalid withdrawal", async () => { const deposit1 = new BN("100000000000000000"); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1, { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: accounts[0] }); // Withdraw more than deposited amount let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1.mul(new BN(2)), sig, { from: accounts[0] }) .should.be.rejectedWith(null, /insufficient funds/); // Token transfer fails await TOKEN1.pause(); sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }) .should.be.rejectedWith(null, /revert/); // ERC20 transfer fails await TOKEN1.unpause(); // Withdraw sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }); // Withdraw again sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }) .should.be.rejectedWith(null, /insufficient funds/); }); it("can deposit and withdraw multiple times", async () => { const deposit1 = new BN("100000000000000000"); const deposit2 = new BN("50000000000000000"); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1.add(deposit2), { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit2, { from: accounts[0] }); // Withdraw let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }); sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit2, sig, { from: accounts[0] }); }); it("can hold ether for a trader", async () => { const deposit1 = new BN("100000000000000000"); const previous = new BN(await web3.eth.getBalance(accounts[0])); // Approve and deposit const fee1 = await testUtils.getFee( renExBalances.deposit(ETH.address, deposit1, { from: accounts[0], value: deposit1.toString() }) ); // Balance should be (previous - fee1 - deposit1) const after = (await web3.eth.getBalance(accounts[0])); after.should.bignumber.equal(previous.sub(fee1).sub(deposit1)); // Withdraw let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], ETH.address); const fee2 = await testUtils.getFee(renExBalances.withdraw(ETH.address, deposit1, sig, { from: accounts[0] })); // Balance should be (previous - fee1 - fee2) (await web3.eth.getBalance(accounts[0])).should.bignumber.equal(previous.sub(fee1).sub(fee2)); }); it("only the settlement contract can call `transferBalanceWithFee`", async () => { await renExBalances.transferBalanceWithFee( accounts[1], accounts[2], REN.address, 1, 0, testUtils.NULL, { from: accounts[1] } ).should.be.rejectedWith(null, /not authorized/); }); it("deposits validates the transfer", async () => { // Token await TOKEN1.approve(renExBalances.address, 1, { from: accounts[1] }); await renExBalances.deposit(TOKEN1.address, 2, { from: accounts[1] }) .should.be.rejectedWith(null, /revert/); // ERC20 transfer fails // ETH await renExBalances.deposit(ETH.address, 2, { from: accounts[1], value: 1 }) .should.be.rejectedWith(null, /mismatched value parameter and tx value/); }); it("transfer validates the fee approval", async () => { const mockSettlement: VersionedContractContract = await VersionedContract.new("VERSION", renExBalances.address); await renExBalances.updateRenExSettlementContract(mockSettlement.address); const token: testUtils.BasicERC20 = await DisapprovingToken.new(); await mockSettlement.transferBalanceWithFee( accounts[1], accounts[2], token.address, 0, 0, testUtils.NULL, // fails to approve to 0x0 ).should.be.rejectedWith(null, /approve failed/); // Revert change await renExBalances.updateRenExSettlementContract(renExSettlement.address); }); it("decrementBalance reverts for invalid withdrawals", async () => { const mockSettlement: VersionedContractContract = await VersionedContract.new("VERSION", renExBalances.address); await renExBalances.updateRenExSettlementContract(mockSettlement.address); const deposit = new BN("10000000000000000"); const doubleDeposit = deposit.mul(new BN(2)); await renExBalances.deposit(ETH.address, deposit, { from: accounts[0], value: deposit.toString() }); // Insufficient balance for fee await mockSettlement.transferBalanceWithFee( accounts[0], accounts[1], ETH.address, 0, doubleDeposit, accounts[0], ).should.be.rejectedWith(null, /insufficient funds for fee/); // Insufficient balance for fee await mockSettlement.transferBalanceWithFee( accounts[0], accounts[1], ETH.address, doubleDeposit, 0, accounts[0], ).should.be.rejectedWith(null, /insufficient funds/); // Revert change await renExBalances.updateRenExSettlementContract(renExSettlement.address); }); it("cannot transfer ether and erc20 in a single transaction", async () => { await TOKEN1.approve(renExBalances.address, 2); await renExBalances.deposit(TOKEN1.address, 2, { value: 2 }) .should.be.rejectedWith(null, /unexpected ether transfer/); }); it("trade is blocked without broker signature", async () => { const deposit1 = new BN("100000000000000000"); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1, { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: accounts[0] }); // Withdraw with null signature await renExBalances.withdraw(TOKEN1.address, deposit1, testUtils.NULL, { from: accounts[0] }) .should.be.rejectedWith(null, /invalid signature/); // Withdraw with invalid signature let invalidSig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[1], ETH.address); await renExBalances.withdraw(ETH.address, deposit1, invalidSig, { from: accounts[0] }) .should.be.rejectedWith(null, /invalid signature/); // Withdraw with no signature await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /not signalled/); }); it("trade can wait 48 hours", async () => { const deposit1 = new BN("100000000000000000"); // Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1.mul(new BN(2)), { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1.mul(new BN(2)), { from: accounts[0] }); let i = 0; await renExBalances.withdraw(TOKEN1.address, deposit1, testUtils.NULL, { from: accounts[0] }) .should.be.rejectedWith(null, /invalid signature/); await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /not signalled/); await renExBalances.signalBackupWithdraw(TOKEN1.address, { from: accounts[0] }); await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /signal time remaining/); // Increase time by 47 hours const hour = 60 * 60; testUtils.increaseTime(47 * hour); await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /signal time remaining/); // Increase time by another hour testUtils.increaseTime(1 * hour + 10); // Still can't withdraw other tokens await renExBalances.withdraw(TOKEN2.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /not signalled/); // Other traders can't withdraw token await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[1] }) .should.be.rejectedWith(null, /not signalled/); // Can now withdraw without signature await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }); // Can only withdraw once await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.be.rejectedWith(null, /not signalled/); // Can withdraw normally let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }); }); it("can subtract transfer fees paid in tokens", async () => { const TUSD = await TUSDToken.deployed(); const fee = new BN(7); const base = new BN(10000); const trader = accounts[1]; const deposit1 = new BN("1000000000000000000"); const fee1 = deposit1.mul(fee).div(base); // [SETUP] Transfer tokens to trader (enough such that it equals deposit1 after fees) await TUSD.transfer(trader, deposit1.mul(base).div(base.sub(fee)).add(new BN(1)), { from: accounts[0] }); // [CHECK] Get ERC20 balance for tokens const previous1 = new BN(await TUSD.balanceOf(trader)); // [ACTION] Approve and deposit await TUSD.approve(renExBalances.address, deposit1, { from: trader }); await renExBalances.deposit(TUSD.address, deposit1, { from: trader }); // [CHECK] Check that balance in renExBalances is updated (await renExBalances.traderBalances(trader, TUSD.address)).should.bignumber.equal(deposit1.sub(fee1)); // [CHECK] Check that the correct amount of tokens has been withdrawn (await TUSD.balanceOf(trader)).should.bignumber.equal(previous1.sub(deposit1)); // [ACTION] Withdraw - and calculate the second transfer fee let sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, trader, TUSD.address); await renExBalances.withdraw(TUSD.address, deposit1.sub(fee1), sig, { from: trader }); const fee2 = (deposit1.sub(fee1)).mul(fee).div(base); // [CHECK] Check that the tokens have been returned (minus the fees) (await TUSD.balanceOf(trader)).should.bignumber.equal(previous1.sub(fee1).sub(fee2)); // [CHECK] Check that balance in renExBalances is zeroed (await renExBalances.traderBalances(trader, TUSD.address)).should.bignumber.equal(0); }); it("withdraw can't be blocked by malicious contract owner", async () => { const deposit1 = new BN("100000000000000000"); const versionedContract: VersionedContractContract = await VersionedContract.new("VERSION", testUtils.NULL); // [SETUP] Approve and deposit await TOKEN1.approve(renExBalances.address, deposit1, { from: accounts[0] }); await renExBalances.deposit(TOKEN1.address, deposit1, { from: accounts[0] }); // [SETUP] const previousSettlementContract = await renExBalances.settlementContract(); const previousRenExBrokerVerifier = await renExBalances.brokerVerifierContract(); const previousDarknodeRewardVault = await renExBalances.rewardVaultContract(); await renExBalances.updateRenExSettlementContract(versionedContract.address); await renExBalances.updateRewardVaultContract(versionedContract.address); await renExBalances.updateBrokerVerifierContract(versionedContract.address); // [CHECK] Can't withdraw normally const sig = await testUtils.signWithdrawal(renExBrokerVerifier, broker, accounts[0], TOKEN1.address); await renExBalances.withdraw(TOKEN1.address, deposit1, sig, { from: accounts[0] }) .should.be.rejectedWith(null, /revert/); // [ACTION] The trader can still withdraw after signalling await renExBalances.signalBackupWithdraw(TOKEN1.address, { from: accounts[0] }); // Increase time by 47 hours const hour = 60 * 60; testUtils.increaseTime(48 * hour + 10); await renExBalances.withdraw(TOKEN1.address, deposit1, "0x", { from: accounts[0] }) .should.not.be.rejected; // [RESET] Reset the contract addresses to the previous addresses await renExBalances.updateRenExSettlementContract(previousSettlementContract); await renExBalances.updateRewardVaultContract(previousRenExBrokerVerifier); await renExBalances.updateBrokerVerifierContract(previousDarknodeRewardVault); }); });
the_stack
import {join, dirname, sep} from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import {spawn} from 'child_process'; import {StreamCatcher} from './streamCatcher'; import * as RX from './regExp'; import variableParser, { ParsedVariable, ParsedVariableScope } from './variableParser'; import { DebugSession } from './session'; import { LocalSession } from './localSession'; import { RemoteSession } from './remoteSession'; import { AttachSession } from './attachSession'; import { PerlDebugSession, LaunchRequestArguments } from './perlDebug'; import { EventEmitter } from 'events'; import { convertToPerlPath } from "./filepath"; import { breakpointParser } from './breakpointParser'; import { platform } from 'os'; import { PerlVersion } from './perlversion'; interface ResponseError { filename: string, ln: number, message: string, near: string, type: string, name: string, } interface WatchpointChange { expression: string; oldValue?: string; newValue?: string; } interface Variable { name: string, type: string, value: any, variablesReference: number, } interface StackFrame { v: string, name: string, filename: string, caller: string, ln: number, } export interface RequestResponse { data?: string[], orgData: string[], ln: number, errors: ResponseError[], name: string, filename: string, exception: boolean, finished: boolean, command?:string, db?:string, changes: WatchpointChange[]; special: string[]; } function findFilenameLine(str: string): string[] { // main::(test.pl:8): const fileMatch = str.match(RX.fileMatch); // at test.pl line 10 const fileMatchException = str.match(RX.fileMatchException); return fileMatch || fileMatchException || []; } function variableType(key: string, val: string): string { if (/^['|"]/.test(val)) { return 'string'; } if (/^([0-9\,\.]+)$/) { return 'integer'; } return 'Unknown'; } function variableValue(val: string): any { if (/^['|"]/.test(val)) { return val.replace(/^'/, '').replace(/'$/, ''); } if (/^([0-9\,\.]+)$/) { return +val; } return val; } function absoluteFilename(root: string, filename: string): string { // if it's already absolute then return if (fs.existsSync(filename)) { return filename; } // otherwise assume it's a relative filename const fullPath = join(root, filename); if (fs.existsSync(fullPath)) { return fullPath; } // xxx: We might want to resolve module names later on // using this.resolveFilename, for now we just return the joined path return join(root, filename); } export class PerlDebuggerConnection extends EventEmitter { public debug: boolean = false; public perlDebugger: DebugSession; public debuggee?: DebugSession; public streamCatcher: StreamCatcher; public perlVersion: PerlVersion; public padwalkerVersion: string; public scopeBaseLevel: number = -1; public develVscodeVersion?: string; public hostname?: string; public commandRunning: string = ''; public canSignalDebugger: boolean = false; public debuggerPid?: number; public programBasename?: string; private filename?: string; private rootPath?: string; /** * Pass in the initial script and optional additional arguments for * running the script. */ constructor() { super(); this.streamCatcher = new StreamCatcher(); } async initializeRequest() { } logOutput(data: string) { this.emit('perl-debug.output', data); } logData(prefix: string, data: string[]) { data.forEach((val, i) => { this.logOutput(`${prefix}${val}`); }); } logDebug(...args: any[]) { this.emit('perl-debug.debug', ...args); if (this.debug) { console.log(...args); } } logRequestResponse(res: RequestResponse) { this.logDebug(res); } parseResponse(data: string[]): RequestResponse { const res: RequestResponse = { data: [], orgData: data, ln: 0, errors: [], name: '', filename: '', exception: false, finished: false, command: '', db: '', changes: [], special: [], }; res.orgData.forEach((line, i) => { if (i === 0) { // Command line res.command = line; } else if (i === res.orgData.length - 1) { // DB const dbX = RX.lastCommandLine.match(line); if (dbX) { res.db = dbX[1]; } } else { // Contents line = line.replace(RX.colors, ''); if (!RX.isGarbageLine(line)) { res.data.push(line); } // Grap the last filename and line number const [, filename, ln] = findFilenameLine(line); if (filename) { res.name = filename; res.filename = absoluteFilename(this.rootPath, filename); res.ln = +ln; } // Check contents for issues if (/^exception/.test(line)) { // xxx: investigate if this is already handled // res.exception = true; } if (/^Daughter DB session started\.\.\./.test(line)) { // TODO(bh): `perl5db.pl` is a bit odd here, when using the // typical `TERM=xterm perl -d` this is printed in the main // console, but with RemotePort set, this seems to launch a // new tty and does nothing with it but print this message. // Might be a good idea to investigate further. } if (/^vscode: /.test(line)) { res.special.push(line); } // Collection of known messages that are not handled in any // special way and probably need not be handled either. But // it might be a good idea to go over them some day and see // if they should be surfaced in the user interface. // // if (/^Loading DB routines from (.*)/.test(line)) { // } // // if (/^Editor support (.*)/.test(line)) { // } // // if (/^Enter h or 'h h' for help, or '.*perldebug' for more help/.test(line)) { // } // // if (/^The old f command is now the r command\./.test(line)) { // } // // if (/^The new f command switches filenames\./.test(line)) { // } // // if (/^No file matching '(.*)' is loaded\./.test(line)) { // } // // if (/^Already in (.*)\./.test(line)) { // } // // if (/^Subroutine (.*) not found\./.test(line)) { // } // // if (/^exec failed: (.*)/.test(line)) { // } // // if (/^(\d+) levels deep in subroutine calls!/.test(line)) { // } // NOTE: this was supposed to handle when `w $$` triggers, // but it turns out `perl5db.pl` prints this to the wrong // tty, that is, in the fork() parent, while the change is // actually in the child. // Watchpoint 0: $example changed: if (RX.watchpointChange.test(line)) { const parts = line.match(RX.watchpointChange); const [, unstableId, expression ] = parts; res.changes.push({ expression: expression, }); } if (RX.watchpointOldval.test(line)) { const parts = line.match(RX.watchpointOldval); const [, oldValue ] = parts; // FIXME(bh): This approach for handling watchpoint changes // is probably not sound if the expression being watched // stringifies as multiple lines. But internally we only // use a single watch expression where this is not an issue // and for data breakpoints configured through vscode user // interface it might be best to wrap expression so that it // would not be possible to get multiple lines in return. res.changes[res.changes.length - 1].oldValue = oldValue; } if (RX.watchpointNewval.test(line)) { const parts = line.match(RX.watchpointNewval); const [, newValue ] = parts; res.changes[res.changes.length - 1].newValue = newValue; } if (/^Debugged program terminated/.test(line)) { res.finished = true; } if (/Use 'q' to quit or 'R' to restart\./.test(line)) { res.finished = true; } if (/^Execution of (\S+) aborted due to compilation errors\.$/.test(line)) { res.exception = true; } if (RX.codeErrorSyntax.test(line)) { const parts = line.match(RX.codeErrorSyntax); if (parts) { const [, filename, ln, near] = parts; res.errors.push({ name: filename, filename: absoluteFilename(this.rootPath, filename), ln: +ln, message: line, near: near, type: 'SYNTAX', }); } } // Undefined subroutine &main::functionNotFound called at broken_code.pl line 10. if (RX.codeErrorRuntime.test(line)) { res.exception = true; const parts = line.match(RX.codeErrorRuntime); if (parts) { const [, near, filename, ln] = parts; res.errors.push({ name: filename, filename: absoluteFilename(this.rootPath, filename), ln: +ln, message: line, near: near, type: 'RUNTIME', }); } } } }); // This happens for example because we replaced `DB::postponed` // with a function that reports newly loaded sources and subs // to us. if (res.special.filter(x => /vscode: new loaded source/.test(x)).length) { this.emit('perl-debug.new-source'); } if (res.special.filter(x => /vscode: new subroutine/.test(x)).length) { this.emit('perl-debug.new-subroutine'); } if (res.finished) { // Close the connection to perl debugger. We try to ask nicely // here, otherwise we might generate a SIGPIPE signal which can // confuse some Perl programs like `prove` during multi-session // debugging. this.request('q') .then(() => this.perlDebugger.kill()) .catch(() => this.perlDebugger.kill()); } if (res.exception) { this.emit('perl-debug.exception', res); } else if (res.finished) { this.emit('perl-debug.termination', res); } if (res.changes.length > 0) { this.emit('perl-debug.databreak', res); } // FIXME(bh): v0.5.0 and earlier of the extension treated all the // debugger commands the same, as if they return quickly and with // a result of some kind. This led to confusion on part of vscode // about whether the debuggee is currently running or stopped. // // We need to send a `StoppedEvent` when the debugger transitions // from executing the debuggee to accepting commands from us, and // must not send a `StoppedEvent` when we are in the middle of // servicing requests from vscode to populate the debug user // interface after a `StoppedEvent`, otherwise vscode will enter // an infinite loop. // // So this is a bit of a kludge to do just that. Better would be // a re-design of how I/O with the debugger works, like having a // `resume(command: string)` method for these special commands, // but that probably requires some surgery through streamCatcher. if (/^[scnr]\b/.test(res.command)) { this.emit('perl-debug.stopped'); } this.logRequestResponse(res); return res; } private async launchRequestAttach( args: LaunchRequestArguments ): Promise<void> { const bindHost = 'localhost'; this.canSignalDebugger = false; this.perlDebugger = new AttachSession(args.port, bindHost); await new Promise( resolve => this.perlDebugger.on("connect", res => resolve(res)) ); } private async launchRequestTerminal( args: LaunchRequestArguments, session: PerlDebugSession ): Promise<void> { this.canSignalDebugger = true; this.logOutput(`Launching program in terminal and waiting`); // NOTE(bh): `localhost` is hardcoded here to ensure that for // local debug sessions, the port is not exposed externally. const bindHost = 'localhost'; this.perlDebugger = new RemoteSession( 0, bindHost, args.sessions ); this.logOutput(this.perlDebugger.title()); // The RemoteSession will listen on a random available port, // and since we need to connect to that port, we have to wait // for it to become available. await new Promise( resolve => this.perlDebugger.on("listening", res => resolve(res)) ); const response = await new Promise((resolve, reject) => { session.runInTerminalRequest({ kind: ( args.console === "integratedTerminal" ? "integrated" : "external" ), cwd: args.root, args: [ args.exec, ...args.execArgs, "-d", args.program, ...args.args ], env: { ...args.env, // TODO(bh): maybe merge user-specified options together // with the RemotePort setting we need? PERLDB_OPTS: `RemotePort=${bindHost}:${this.perlDebugger.port}`, } }, 5000, response => { if (response.success) { resolve(response); } else { reject(response); } }); }); } private async launchRequestNone( args: LaunchRequestArguments ): Promise<void> { const bindHost = 'localhost'; this.canSignalDebugger = true; this.perlDebugger = new RemoteSession( 0, bindHost, args.sessions ); this.logOutput(this.perlDebugger.title()); await new Promise( resolve => this.perlDebugger.on("listening", res => resolve(res)) ); this.debuggee = new LocalSession({ ...args, program: args.program, root: args.root, args: args.args, env: { ...args.env, // TODO(bh): maybe merge user-specified options together // with the RemotePort setting we need? PERLDB_OPTS: `RemotePort=${bindHost}:${this.perlDebugger.port}`, } }); } private async launchRequestRemote( args: LaunchRequestArguments ): Promise<void> { // FIXME(bh): Logging the port here makes no sense when the // port is set to zero (which causes random one to be selected) this.logOutput( `Waiting for remote debugger to connect on port "${args.port}"` ); this.perlDebugger = new RemoteSession( args.port, '0.0.0.0', args.sessions ); this.canSignalDebugger = false; // FIXME(bh): this does not await the listening event since we // already know the port number beforehand, and probably we do // still wait (due to the streamCatcher perhaps?) for streams // to become usable, it still seems weird though to not await. } async launchSession( args: LaunchRequestArguments, session: PerlDebugSession ) { switch (args.console) { case "integratedTerminal": case "externalTerminal": { if (!session || !session.dcSupportsRunInTerminal) { // FIXME(bh): better error handling. this.logOutput( `Error: console:${args.console} unavailable` ); break; } await this.launchRequestTerminal( args, session ); break; } case "remote": { await this.launchRequestRemote(args); break; } case "none": { await this.launchRequestNone(args); break; } case "_attach": { await this.launchRequestAttach(args); break; } default: { // FIXME(bh): better error handling? Perhaps override bad // values earlier in `resolveDebugConfiguration`? this.logOutput( `Error: console: ${args.console} unknown` ); break; } } } private async canSignalHeuristic(): Promise<boolean> { // Execution control requests such as `terminate` and `pause` are // at least in part implemented through sending signals to the // debugger/debuggee process. That can only be done on the local // system. But users might use remote debug configurations on the // local machine, in which case it would be a shame if `pause` // did not work. // // There is no easy and portable way to generate something like a // globally unique process identifier that could be used to make // sure we actually are on the same system, but a heuristic might // be fair enough. If it looks as though Perl can signal us, and // we can signal Perl, and we think we run on systems with the // same hostname, we simply assume that we in fact do so. // // On Linux `/proc/sys/kernel/random/boot_id` could be compared, // if we and Perl see the same contents, we very probably are on // the same system. Similarily, other `/proc/` details could be // compared. We cannot use socket address comparisons since the // user might have their own forwarding setup in place. if (os.hostname() !== this.hostname) { return false; } const debuggerCanSignalUs = await this.getExpressionValue( `CORE::kill(0, ${process.pid})` ); if (!debuggerCanSignalUs) { return false; } try { process.kill(this.debuggerPid, 0); } catch (e) { return false; } return true; } private async installSubroutines() { // https://metacpan.org/pod/Devel::vscode register a namespace // on CPAN for use in this extension. For some features, we have // to execute Perl code in the debugger, and sometimes it can be // unwieldy to send the whole code to the debugger every time. // There are also features that benefit from persisting data on // Perl's end. So this installs a couple of subroutines for such // features. For these, it is not necessary for users of the // extension to install or otherwise load `Devel::vscode`. const singleLine = (strings, ...args) => { return strings.join('').replace(/\n/g, " "); }; const unreportedSources = singleLine` sub Devel::vscode::_unreportedSources { return join "\t", grep { my $old = $Devel::vscode::_reportedSources{$_}; $Devel::vscode::_reportedSources{$_} = $$; not defined $old or $old ne $$ } grep { /^_<[^(]/ } keys %main:: } `; // Perl stores file source code in `@{main::_<example.pl}` // arrays. This retrieves the code in %xx-escaped form to // ensure we only get a single line of output. const getSourceCode = singleLine` sub Devel::vscode::_getSourceCode { local $_ = join("", @{"main::_<@_"}); s/([^a-zA-Z0-9\\x{80}-\\x{10FFFF}])/ sprintf '%%%02x', ord "$1"/ge; return $_ } `; // As perl `perldebuts`, "After each required file is compiled, // but before it is executed, DB::postponed(*{"_<$filename"}) is // called if the subroutine DB::postponed exists." and "After // each subroutine subname is compiled, the existence of // $DB::postponed{subname} is checked. If this key exists, // DB::postponed(subname) is called if the DB::postponed // subroutine also exists." // // Overriding the function with a thin wrapper like this would // give us a chance to report any newly loaded source directly // instead of repeatedly polling for it, which could be used to // make breakpoints more reliable. Same probably for function // breakpoints if they are registered as explained above. // // Note that when a Perl process is `fork`ed, we may already have // wrapped the original function and must avoid doing it again. // This is not actually used at the moment. We cannot usefully // break into the debugger here, since there is no good way to // resume exactly as the user originally intended. There would // have to be a way to process such messages asynchronously as // they arrive. const breakOnLoad = singleLine` package DB; *DB::postponed = sub { my ($old_postponed) = @_; $Devel::vscode::_overrodePostponed = 1; return sub { if ('GLOB' eq ref(\\$_[0]) and $_[0] =~ /<(.*)\s*$/s) { print { $DB::OUT } "vscode: new loaded source $1\\n"; } else { print { $DB::OUT } "vscode: new subroutine $_[0]\\n"; } &{$old_postponed}; }; }->(\\&DB::postponed) unless $Devel::vscode::_overrodePostponed; `; await this.request(unreportedSources); await this.request(getSourceCode); await this.request(breakOnLoad); } async launchRequest( args: LaunchRequestArguments, session: PerlDebugSession ): Promise<RequestResponse> { this.rootPath = args.root; this.filename = args.program; this.logDebug(`Platform: ${platform()}`); Object.keys(args.env || {}).forEach(key => { this.logDebug(`env.${key}: "${args.env[key]}"`); }); // Verify file and folder existence // xxx: We can improve the error handling // FIXME(bh): does it make sense to have a source file here when // we just create a server for a remote client to connect to? It // seems it should be possible to `F5` without specifying a file. // FIXME(bh): Check needs to account for args.root if (!fs.existsSync(args.program)) { this.logOutput(`Error: File ${args.program} not found`); } if (args.root && !fs.existsSync(args.root)) { this.logOutput(`Error: Folder ${args.root} not found`); } this.logOutput(`Platform: ${platform()}`); // This is the actual launch await this.launchSession(args, session); this.commandRunning = this.perlDebugger.title(); this.perlDebugger.on('error', (err) => { this.logDebug('error:', err); this.logOutput( `Error`); this.logOutput( err ); this.logOutput( `DUMP: ${this.perlDebugger.title()}` ); }); // Handle program output this.perlDebugger.stdout.on('data', (buffer) => { const data = buffer.toString().split('\n'); this.logData('', data); // xxx: Program output, better formatting/colors? }); this.perlDebugger.on('close', (code) => { this.commandRunning = ''; this.logOutput(`Debugger connection closed`); this.emit('perl-debug.close', code); }); this.perlDebugger.on( 'perl-debug.attachable.listening', data => { this.emit( 'perl-debug.attachable.listening', data ); }); this.streamCatcher.removeAllListeners(); this.streamCatcher.on('perl-debug.streamcatcher.data', (...x) => { this.emit( 'perl-debug.streamcatcher.data', this.perlDebugger.title(), ...x ); }); this.streamCatcher.on('perl-debug.streamcatcher.write', (...x) => { this.emit( 'perl-debug.streamcatcher.write', this.perlDebugger.title(), ...x ); }); const data = await this.streamCatcher.launch( this.perlDebugger.stdin, this.perlDebugger.stderr ); if (args.sessions !== 'single') { this.develVscodeVersion = await this.getDevelVscodeVersion(); if (!this.develVscodeVersion) { // Global watch expression that breaks into the debugger when // the pid of the process changes; that can only happen right // after a fork. This is needed to learn about new children // when Devel::vscode is not loaded, see documentation there. await this.streamCatcher.request( 'w $$' ); } } // NOTE(bh): By default warnings should be shown in the terminal // where the debugee's STDERR is shown. However, some versions of // Perl default https://rt.perl.org/Ticket/Display.html?id=133875 // to redirecting warning output into the debugger's STDERR, so // we undo that here. await this.streamCatcher.request( 'o warnLevel=0' ); // this.streamCatcher.debug = this.debug; // Depend on the data dumper for the watcher // await this.streamCatcher.request('use Data::Dumper'); await this.streamCatcher.request('$DB::single = 1;'); // NOTE(bh): Since we are no longer connected directly to the // debuggee when interacting with the debugger, there is no need // to do this anymore. The `$DB::OUT` handle is set to autoflush // by `perl5db.pl` already and it does not have an output handle // besides of that. Doing this changes the debuggee's autoflush // behavior which we should not do if at all avoidable. // xxx: Prevent buffering issues ref: https://github.com/raix/vscode-perl-debug/issues/15#issuecomment-331435911 // await this.streamCatcher.request('$| = 1;'); // Initial data from debugger this.logData('', data.slice(0, data.length-2)); // While `runInTerminal` is supposed to give us the pid of the // spawned `perl -d` process, that does not work very well as of // 2019-02. Instead we ask Perl for the host process id. Note // that the value is meaningful only if `this.isRemote` is false. // For local processes the pid is needed to send `SIGINT` to the // debugger, which is supposed to break into the debugger and // used to implement the `pauseRequest`. this.debuggerPid = await this.getDebuggerPid(); this.programBasename = await this.getProgramBasename(); this.hostname = await this.getHostname(); // Try to find out if debug adapter and debugger run on the same // machine and can signal each other even if the launchRequest is // configured for remote debugging or an attach session, so users // can pause and terminate processes through the user interface. if (!this.canSignalDebugger) { this.canSignalDebugger = await this.canSignalHeuristic(); } try { // Get the version just after this.perlVersion = new PerlVersion(await this.getPerlVersion()); } catch(ignore) { // xxx: We have to ignore this error because it would intercept the true // error on windows } try { this.padwalkerVersion = await this.getPadwalkerVersion(); } catch(ignore) { // xxx: Ignore errors - it should not break anything, this is used to // inform the user of a missing dependency install of PadWalker } if (this.padwalkerVersion.length > 0) { try { this.scopeBaseLevel = await this.getVariableBaseLevel(); } catch (ignore) { // ignore the error } } await this.installSubroutines(); return this.parseResponse(data); } async request(command: string): Promise<RequestResponse> { return this.parseResponse(await this.streamCatcher.request(command)); } async relativePath(filename: string) { return path.relative(this.rootPath, filename || ''); } async setFileContext(filename: string = this.filename) { // xxx: Apparently perl DB wants unix path separators on windows so // we enforce the unix separator. Also remove relative path steps; // if the debugger does not know about a file path literally, it // will try to find a matching file through a regex match, so this // increases the odds of finding the right file considerably. An // underlying issue here is that we cannot always use resolved // paths because we do not know what a relative path is relative // to. const cleanFilename = convertToPerlPath(filename); // await this.request(`print STDERR "${cleanFilename}"`); const res = await this.request(`f ${cleanFilename}`); if (res.data.length) { // if (/Already in/.test) if (/^No file matching/.test(res.data[0])) { throw new Error(res.data[0]); } } return res; } async setBreakPoint(ln: number, filename?: string): Promise<RequestResponse> { // xxx: We call `b ${filename}:${ln}` but this will not complain // about files not found - this might be ok for now // await this.setFileContext(filename); // const command = filename ? `b ${filename}:${ln}` : `b ${ln}`; // const res = await this.request(`b ${ln}`); return Promise.all([this.setFileContext(filename), this.request(`b ${ln}`)]) .then(result => { const res = <RequestResponse>result.pop(); this.logRequestResponse(res); if (res.data.length) { if (/not breakable\.$/.test(res.data[0])) { throw new Error(res.data[0] + ' ' + filename + ':' + ln); } if (/not found\.$/.test(res.data[0])) { throw new Error(res.data[0] + ' ' + filename + ':' + ln); } } return res; }); } async getBreakPoints() { const res = await this.request(`L b`); this.logRequestResponse(res); const breakpoints = breakpointParser(res.data); this.logDebug('BREAKPOINTS:', breakpoints); return breakpoints; } clearBreakPoint(ln: number, filename?: string): Promise<RequestResponse> { // xxx: We call `B ${filename}:${ln}` but this will not complain // about files not found - not sure if it's a bug or not but // the perl debugger will change the main filename to filenames // not found - a bit odd // await this.setFileContext(filename); // const command = filename ? `B ${filename}:${ln}` : `B ${ln}`; return Promise.all([this.setFileContext(filename), this.request(`B ${ln}`)]) .then(results => <RequestResponse>results.pop()); } async clearAllBreakPoints() { return await this.request('B *'); } async continue() { return await this.request('c'); } // Next: async next() { return await this.request('n'); } async restart() { // xxx: We might need to respawn on windows return await this.request('R'); } async getVariableReference(name: string): Promise<string> { const res = await this.request(`p \\${name}`); return res.data[0]; } async getExpressionValue(expression: string): Promise<string> { const res = await this.request(`p ${expression}`); return res.data.pop(); } /** * Prints out a nice indent formatted list of variables with * array references resolved. */ async requestVariableOutput(level: number) { const variables: Variable[] = []; const res = await this.request(`y ${level + this.scopeBaseLevel - 1}`); const result = []; if (/^Not nested deeply enough/.test(res.data[0])) { return []; } if (RX.codeErrorMissingModule.test(res.data[0])) { throw new Error(res.data[0]); } // Resolve all Array references for (let i = 0; i < res.data.length; i++) { const line = res.data[i]; if (/\($/.test(line)) { const name = line.split(' = ')[0]; const reference = await this.getVariableReference(name); result.push(`${name} = ${reference}`); } else if (line !== ')') { result.push(line); } } return result; } async getVariableList(level: number, scopeName?: string): Promise<ParsedVariableScope> { const variableOutput = await this.requestVariableOutput(level); //console.log('RESOLVED:'); //console.log(variableOutput); return variableParser(variableOutput, scopeName); } async variableList(scopes): Promise<ParsedVariableScope> { // If padwalker not found then tell the user via the variable inspection // instead of being empty. if (!this.padwalkerVersion) { return { local_0: [{ name: 'PadWalker', value: 'Not installed', type: 'string', variablesReference: '0', }], }; } const keys = Object.keys(scopes); let result: ParsedVariableScope = {}; for (let i = 0; i < keys.length; i++) { const name = keys[i]; const level = scopes[name]; Object.assign(result, await this.getVariableList(level, name)); } return result; } async getStackTrace(): Promise<StackFrame[]> { const res = await this.request('T'); const result: StackFrame[] = []; res.data.forEach((line, i) => { // > @ = DB::DB called from file 'lib/Module2.pm' line 5 // > . = Module2::test2() called from file 'test.pl' line 12 const m = line.match(/^(\S+) = (\S+) called from file \'(\S+)\' line ([0-9]+)$/); if (m !== null) { const [, v, caller, name, ln] = m; const filename = absoluteFilename(this.rootPath, name); result.push({ v, name, filename, caller, ln: +ln, }); } }); return result; } async getLoadedFiles(): Promise<string[]> { const loadedFiles = await this.getExpressionValue( 'Devel::vscode::_unreportedSources() if defined &Devel::vscode::_unreportedSources' ); return (loadedFiles || '') .split(/\t/) .filter(x => !/^_<\(eval \d+\)/.test(x)) .map(x => x.replace(/^_</, '')); } async getSourceCode(perlPath: string): Promise<string> { // NOTE: `perlPath` must be a path known to Perl, there is // no path translation at this point. const escapedPath = this.escapeForSingleQuotes(perlPath); return decodeURIComponent( await this.getExpressionValue( `Devel::vscode::_getSourceCode('${escapedPath}')` ) ); } async watchExpression(expression) { // Brute force this a bit... return Promise.all([ this.request(`W ${expression}`), this.request(`w ${expression}`), ]) .then(res => res.pop()); } async clearAllWatchers() { return this.request('W *'); } async getPerlVersion(): Promise<string> { return this.getExpressionValue('$]'); } async getPadwalkerVersion(): Promise<string> { const res = await this.request( 'p sub { local $@; eval "require PadWalker; PadWalker->VERSION()" }->()' ); const version = res.data[0]; if (/^[0-9]+\.?([0-9]?)+$/.test(version)) { return version; } return JSON.stringify(res.data); } async getVariableBaseLevel() { const limitOfScope = /^Not nested deeply enough/; const {data: [level1]} = await this.request('y 1'); // 5.22 const {data: [level2]} = await this.request('y 2'); // 5.20 if (limitOfScope.test(level1)) { return 0; } if (limitOfScope.test(level2)) { return 1; } // apparently we didn't find the base level? return -1; } async getDebuggerPid(): Promise<number> { const res = await this.request( 'p $$' ); return parseInt(res.data[0]); } async getHostname(): Promise<string> { const res = await this.request( 'p sub { local $@; eval "require Sys::Hostname; Sys::Hostname::hostname()" }->()' ); return res.data[0]; } async getDevelVscodeVersion(): Promise<string | undefined> { const res = await this.request( 'p sub { local $@; eval "\$Devel::vscode::VERSION" }->()' ); const [ result = undefined ] = res.data; return result; } async getProgramBasename(): Promise<string> { const res = await this.request( 'p $0' ); return (res.data[0] || '').replace(/.*[\/\\](.*)/, '$1'); } public getThreadName(): string { return `${this.programBasename} (pid ${ this.debuggerPid} on ${ this.hostname})`; } async resolveFilename(filename): Promise<string> { const res = await this.request(`p $INC{"${filename}"};`); const [ result = '' ] = res.data; return result; } public escapeForSingleQuotes(unescaped: string): string { return unescaped.replace( /([\\'])/g, '\\$1' ); } public terminateDebugger(): boolean { if (this.canSignalDebugger) { // Send SIGTERM to the `perl -d` process on the local system. process.kill(this.debuggerPid, 'SIGTERM'); return true; } else { return false; } } async destroy() { if (this.perlDebugger) { this.streamCatcher.destroy(); this.perlDebugger.kill(); this.perlDebugger = null; } if (this.debuggee) { this.debuggee.kill(); this.debuggee = null; } } }
the_stack
import * as React from 'react'; import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base'; import { SPComponentLoader } from '@microsoft/sp-loader'; import { CalloutTriggers } from '@pnp/spfx-property-controls/lib/PropertyFieldHeader'; import { PropertyFieldSliderWithCallout } from '@pnp/spfx-property-controls/lib/PropertyFieldSliderWithCallout'; import { PropertyFieldToggleWithCallout } from '@pnp/spfx-property-controls/lib/PropertyFieldToggleWithCallout'; import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker'; import * as _ from "lodash"; import * as moment from 'moment'; import styles from './PageCommentsWebPart.module.scss'; import * as strings from 'PageCommentsWebPartStrings'; import * as $ from 'jquery'; require('textcomplete'); import { sp } from '@pnp/sp'; import SPHelper from './SPHelper'; require('./css/jquery-comments.css'); export interface IPageCommentsWebPartProps { enableNavigation: boolean; enableReplying: boolean; enableAttachments: boolean; enableEditing: boolean; enableUpvoting: boolean; enableDeleting: boolean; enableDeletingCommentWithReplies: boolean; enableHashtags: boolean; enablePinging: boolean; enableDocumentPreview: boolean; roundProfilePictures: boolean; datetimeFormat: string; attachmentFileFormats: string; attachmentFileSize: number; docLib: string; } export default class PageCommentsWebPart extends BaseClientSideWebPart<IPageCommentsWebPartProps> { private helper: SPHelper = null; private currentUserInfo: any = null; private siteUsers: any[] = []; private pageurl: string = ''; private postAttachmentPath: string = ''; private pageFolderExists: boolean = false; protected async onInit(): Promise<void> { await super.onInit(); sp.setup(this.context); } public constructor() { super(); SPComponentLoader.loadCss("https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"); } public render(): void { if (this.properties.enableAttachments && (this.properties.docLib === null || undefined === this.properties.docLib || this.properties.docLib.toLocaleUpperCase() === "NO_LIST_SELECTED")) { this.domElement.innerHTML = ` <div class="${styles.errorMessage}"><i class="fa fa-times-circle" aria-hidden="true"></i>&nbsp;${strings.NoAttachmentRepoMsg}</div> `; } else { this.context.statusRenderer.displayLoadingIndicator(this.domElement, strings.LoadingMsg, 0); this.checkAndCreateList(); } } private async checkAndCreateList() { if (this.properties.enableAttachments) { this.helper = new SPHelper(this.properties.docLib); } else { this.helper = new SPHelper(); } await this.helper.checkListExists(); this.initializeComments(); } private initializeComments = async () => { this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.domElement.innerHTML = ` <div class="${ styles.pageComments}"> <div class="${ styles.container}"> <div class="${ styles.row}"> <div id="page-comments"></div> </div> </div> </div>`; var self = this; if (this.properties.enableAttachments) { await this.helper.getDocLibInfo(); this.postAttachmentPath = await this.helper.getPostAttachmentFilePath(this.pageurl); this.pageFolderExists = await this.helper.checkForPageFolder(this.postAttachmentPath); } this.pageurl = this.context.pageContext.legacyPageContext.serverRequestPath; this.currentUserInfo = await this.helper.getCurrentUserInfo(); this.siteUsers = await this.helper.getSiteUsers(self.currentUserInfo.ID); require(['jquery', './js/jquery-comments.min'], (jQuery, comments) => { jQuery('#page-comments').comments({ profilePictureURL: self.currentUserInfo.Picture, currentUserId: self.currentUserInfo.ID, maxRepliesVisible: 3, textareaRows: 1, textareaRowsOnFocus: 2, textareaMaxRows: 5, highlightColor: '#b5121b', attachmentFileFormats: self.properties.attachmentFileFormats !== undefined ? self.properties.attachmentFileFormats : 'audio/*,image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx', attachmentFileSize: self.properties.attachmentFileSize !== undefined ? self.properties.attachmentFileSize : 5, siteURL: self.context.pageContext.legacyPageContext.webServerRelativeUrl, enableNavigation: self.properties.enableNavigation !== undefined ? self.properties.enableNavigation : true, enableReplying: self.properties.enableReplying !== undefined ? self.properties.enableReplying : true, enableEditing: self.properties.enableEditing !== undefined ? self.properties.enableEditing : false, enableUpvoting: self.properties.enableUpvoting !== undefined ? self.properties.enableUpvoting : true, enableDeleting: self.properties.enableDeleting !== undefined ? self.properties.enableDeleting : false, enableAttachments: self.properties.enableAttachments !== undefined ? self.properties.enableAttachments : false, enableHashtags: self.properties.enableHashtags !== undefined ? self.properties.enableHashtags : false, enablePinging: self.properties.enablePinging !== undefined ? self.properties.enablePinging : false, enableDocumentPreview: self.properties.enableDocumentPreview !== undefined ? self.properties.enableDocumentPreview : false, roundProfilePictures: self.properties.roundProfilePictures !== undefined ? self.properties.roundProfilePictures : true, timeFormatter: (time) => { try { if (self.properties.datetimeFormat) { return moment(time).format(self.properties.datetimeFormat); } else return moment(time).format(self.properties.datetimeFormat); } catch (err) { return moment(time).format("DD/MM/YYYY hh:mm:ss A"); } }, getComments: async (success, error) => { let commentsArray = await self.helper.getPostComments(self.pageurl, self.currentUserInfo); if (commentsArray.length > 0) { var fil = _.filter(commentsArray, (o) => { return moment(o.created).format("DD/MM/YYYY") === moment().format("DD/MM/YYYY"); }); fil.map((comment) => { _.set(comment, 'is_new', true); }); fil = _.filter(commentsArray, (o) => { return o.userid == self.currentUserInfo.ID; }); fil.map((comment) => { _.set(comment, 'created_by_current_user', true); }); } success(commentsArray); }, postComment: async (commentJson, success, error) => { commentJson.fullname = self.currentUserInfo.DisplayName; commentJson.userid = self.currentUserInfo.ID; commentJson = self.saveComment(commentJson); await self.helper.postComment(self.pageurl, commentJson, self.currentUserInfo); if (moment(commentJson.created).format("DD/MM/YYYY") === moment().format("DD/MM/YYYY")) _.set(commentJson, 'is_new', true); _.set(commentJson, 'created_by_current_user', true); success(commentJson); }, searchUsers: async (term, success, error) => { let res = []; if (self.siteUsers.length <= 0) self.siteUsers = await self.helper.getSiteUsers(self.currentUserInfo.ID); res = _.chain(self.siteUsers).filter((o) => { return o.fullname.toLowerCase().indexOf(term) >= 0 || o.email.toLowerCase().indexOf(term) >= 0; }).take(10).value(); success(res); }, upvoteComment: async (commentJSON, success, error) => { await self.helper.voteComment(self.pageurl, commentJSON, self.currentUserInfo); success(commentJSON); }, deleteComment: async (commentJSON, success, error) => { await self.helper.deleteComment(self.pageurl, commentJSON); success(); }, putComment: async (commentJSON, success, error) => { commentJSON = self.saveComment(commentJSON); await self.helper.editComments(self.pageurl, commentJSON); success(commentJSON); }, uploadAttachments: async (commentArray, success, error) => { let res = await self.helper.postAttachments(commentArray, self.pageFolderExists, self.postAttachmentPath); _.merge(res[0], { userid: self.currentUserInfo.ID, fullname: self.currentUserInfo.DisplayName }); await self.helper.postComment(self.pageurl, res[0], self.currentUserInfo); if (moment(res[0].created).format("DD/MM/YYYY") === moment().format("DD/MM/YYYY")) _.set(res[0], 'is_new', true); _.set(res[0], 'created_by_current_user', true); success(res); } }); }); } private saveComment = (data) => { // Convert pings to human readable format $(Object.keys(data.pings)).each((index, userId) => { var fullname = data.pings[`${userId}`]; var pingText = '@' + fullname; data.content = data.content.replace(new RegExp('@' + userId, 'g'), pingText); }); return data; } private checkForDocumentLibrary = (value: string): string => { if (value === null || value.trim().length === 0 || value.toLocaleUpperCase() === "NO_LIST_SELECTED") { return strings.AttachmentRepoPropValMsg; } return ''; } protected get disableReactivePropertyChanges(): boolean { return true; } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('datetimeFormat', { label: strings.DateTimeFormatLabel, description: strings.DateTimeFormatDescription, multiline: false, resizable: false, value: this.properties.datetimeFormat }), PropertyFieldToggleWithCallout('roundProfilePictures', { calloutTrigger: CalloutTriggers.Hover, key: 'roundProfilePicturesFieldId', label: strings.RoundProfilePicLabel, calloutContent: React.createElement('p', {}, strings.RoundProfilePicDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.roundProfilePictures !== undefined ? this.properties.roundProfilePictures : true }), PropertyFieldToggleWithCallout('enableNavigation', { calloutTrigger: CalloutTriggers.Hover, key: 'enableNavigationFieldId', label: strings.NavigationLabel, calloutContent: React.createElement('p', {}, strings.NavigationDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableNavigation !== undefined ? this.properties.enableNavigation : true }), PropertyFieldToggleWithCallout('enableAttachments', { calloutTrigger: CalloutTriggers.Hover, key: 'enableAttachmentsFieldId', label: strings.AttachmentLabel, calloutContent: React.createElement('p', {}, strings.AttachmentDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableAttachments !== undefined ? this.properties.enableAttachments : false }), PropertyFieldListPicker('docLib', { label: strings.AttachmentRepoLabel, selectedList: this.properties.docLib, includeHidden: false, orderBy: PropertyFieldListPickerOrderBy.Title, onPropertyChange: this.onPropertyPaneFieldChanged.bind(this), properties: this.properties, context: this.context, onGetErrorMessage: this.checkForDocumentLibrary.bind(this), deferredValidationTime: 0, key: 'docLibFieldId', baseTemplate: 101, disabled: !this.properties.enableAttachments }), PropertyPaneTextField('attachmentFileFormats', { label: strings.AttachmentFileFormatLabel, description: strings.AttachmentFileFormatDescription, multiline: false, resizable: false, value: this.properties.attachmentFileFormats, disabled: !this.properties.enableAttachments }), PropertyFieldSliderWithCallout('attachmentFileSize', { calloutContent: React.createElement('div', {}, strings.AttachmentFileSizeDescription), calloutTrigger: CalloutTriggers.Hover, calloutWidth: 200, key: 'attachmentFileSizeFieldId', label: strings.AttachmentFileSizeLabel, max: 10, min: 1, step: 1, showValue: true, value: this.properties.attachmentFileSize, disabled: !this.properties.enableAttachments }), PropertyFieldToggleWithCallout('enablePinging', { calloutTrigger: CalloutTriggers.Hover, key: 'enablePingingFieldId', label: strings.PingLabel, calloutContent: React.createElement('p', {}, strings.PingDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enablePinging !== undefined ? this.properties.enablePinging : false }), PropertyFieldToggleWithCallout('enableEditing', { calloutTrigger: CalloutTriggers.Hover, key: 'enableEditingFieldId', label: strings.EditingLabel, calloutContent: React.createElement('p', {}, strings.EditingDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableEditing !== undefined ? this.properties.enableEditing : false }), PropertyFieldToggleWithCallout('enableDeleting', { calloutTrigger: CalloutTriggers.Hover, key: 'enableDeletingFieldId', label: strings.DeleteLabel, calloutContent: React.createElement('p', {}, strings.DeleteDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableDeleting !== undefined ? this.properties.enableDeleting : false, disabled: !this.properties.enableEditing }), // PropertyFieldToggleWithCallout('enableDeletingCommentWithReplies', { // calloutTrigger: CalloutTriggers.Hover, // key: 'enableDeletingCommentWithRepliesFieldId', // label: strings.DeleteRepliesLabel, // calloutContent: React.createElement('p', {}, strings.DeleteRepliesDescription), // onText: 'Enable', // offText: 'Disable', // checked: this.properties.enableDeletingCommentWithReplies, // disabled: !this.properties.enableEditing // }), PropertyFieldToggleWithCallout('enableUpvoting', { calloutTrigger: CalloutTriggers.Hover, key: 'enableUpvotingFieldId', label: strings.UpVotingLabel, calloutContent: React.createElement('p', {}, strings.UpVotingDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableUpvoting !== undefined ? this.properties.enableUpvoting : true }), PropertyFieldToggleWithCallout('enableReplying', { calloutTrigger: CalloutTriggers.Hover, key: 'enableReplyingFieldId', label: strings.ReplyLabel, calloutContent: React.createElement('p', {}, strings.ReplyDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableReplying !== undefined ? this.properties.enableReplying : true }), PropertyFieldToggleWithCallout('enableHashtags', { calloutTrigger: CalloutTriggers.Hover, key: 'enableHashtagsFieldId', label: strings.HashtagsLabel, calloutContent: React.createElement('p', {}, strings.HashtagsDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableHashtags !== undefined ? this.properties.enableHashtags : false }), PropertyFieldToggleWithCallout('enableDocumentPreview', { calloutTrigger: CalloutTriggers.Hover, key: 'enableDocumentPreviewFieldId', label: strings.DocumentPreviewLabel, calloutContent: React.createElement('p', {}, strings.DocumentPreviewDescription), onText: 'Enable', offText: 'Disable', checked: this.properties.enableDocumentPreview !== undefined ? this.properties.enableDocumentPreview : false }), ] } ] } ] }; } }
the_stack
import { CoreError } from '@classes/errors/error'; import { SQLiteDB, SQLiteDBRecordValue, SQLiteDBRecordValues } from '@classes/sqlitedb'; /** * Wrapper used to interact with a database table. */ export class CoreDatabaseTable< DBRecord extends SQLiteDBRecordValues = SQLiteDBRecordValues, PrimaryKeyColumn extends keyof DBRecord = 'id', PrimaryKey extends GetDBRecordPrimaryKey<DBRecord, PrimaryKeyColumn> = GetDBRecordPrimaryKey<DBRecord, PrimaryKeyColumn> > { protected config: Partial<CoreDatabaseConfiguration>; protected database: SQLiteDB; protected tableName: string; protected primaryKeyColumns: PrimaryKeyColumn[]; protected listeners: CoreDatabaseTableListener[] = []; constructor( config: Partial<CoreDatabaseConfiguration>, database: SQLiteDB, tableName: string, primaryKeyColumns?: PrimaryKeyColumn[], ) { this.config = config; this.database = database; this.tableName = tableName; this.primaryKeyColumns = primaryKeyColumns ?? ['id'] as PrimaryKeyColumn[]; } /** * Get database configuration. */ getConfig(): Partial<CoreDatabaseConfiguration> { return this.config; } /** * Get database connection. * * @returns Database connection. */ getDatabase(): SQLiteDB { return this.database; } /** * Get table name. * * @returns Table name. */ getTableName(): string { return this.tableName; } /** * Get primary key columns. * * @returns Primary key columns. */ getPrimaryKeyColumns(): PrimaryKeyColumn[] { return this.primaryKeyColumns.slice(0); } /** * Initialize. */ async initialize(): Promise<void> { // Nothing to initialize by default, override this method if necessary. } /** * Destroy. */ async destroy(): Promise<void> { this.listeners.forEach(listener => listener.onDestroy?.()); } /** * Add listener. * * @param listener Listener. */ addListener(listener: CoreDatabaseTableListener): void { this.listeners.push(listener); } /** * Check whether the table matches the given configuration for the values that concern it. * * @param config Database config. * @returns Whether the table matches the given configuration. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars matchesConfig(config: Partial<CoreDatabaseConfiguration>): boolean { return true; } /** * Get records matching the given conditions. * * @param conditions Matching conditions. If this argument is missing, all records in the table will be returned. * @param options Query options. * @returns Database records. */ getMany(conditions?: Partial<DBRecord>, options?: Partial<CoreDatabaseQueryOptions<DBRecord>>): Promise<DBRecord[]> { if (!conditions && !options) { return this.database.getAllRecords(this.tableName); } const sorting = options?.sorting && this.normalizedSorting(options.sorting).map(([column, direction]) => `${column} ${direction}`).join(', '); return this.database.getRecords(this.tableName, conditions, sorting, '*', options?.offset, options?.limit); } /** * Get records matching the given conditions. * * This method should be used when it's necessary to apply complex conditions; the simple `getMany` * method should be favored otherwise for better performance. * * @param conditions Matching conditions in SQL and JavaScript. */ getManyWhere(conditions: CoreDatabaseConditions<DBRecord>): Promise<DBRecord[]> { return this.database.getRecordsSelect(this.tableName, conditions.sql, conditions.sqlParams); } /** * Find one record matching the given conditions. * * @param conditions Matching conditions. * @param options Result options. * @returns Database record. */ async getOne( conditions?: Partial<DBRecord>, options?: Partial<Omit<CoreDatabaseQueryOptions<DBRecord>, 'offset' | 'limit'>>, ): Promise<DBRecord> { if (!options) { return this.database.getRecord<DBRecord>(this.tableName, conditions); } const records = await this.getMany(conditions, { ...options, limit: 1, }); if (records.length === 0) { throw new CoreError('No records found.'); } return records[0]; } /** * Find one record by its primary key. * * @param primaryKey Primary key. * @returns Database record. */ getOneByPrimaryKey(primaryKey: PrimaryKey): Promise<DBRecord> { return this.database.getRecord<DBRecord>(this.tableName, primaryKey); } /** * Reduce some records into a single value. * * @param reducer Reducer functions in SQL and JavaScript. * @param conditions Matching conditions in SQL and JavaScript. If this argument is missing, all records in the table * will be used. * @returns Reduced value. */ reduce<T>(reducer: CoreDatabaseReducer<DBRecord, T>, conditions?: CoreDatabaseConditions<DBRecord>): Promise<T> { return this.database.getFieldSql( `SELECT ${reducer.sql} FROM ${this.tableName} ${conditions?.sql ?? ''}`, conditions?.sqlParams, ) as unknown as Promise<T>; } /** * Check whether the table is empty or not. * * @returns Whether the table is empty or not. */ isEmpty(): Promise<boolean> { return this.hasAny(); } /** * Check whether the table has any record matching the given conditions. * * @param conditions Matching conditions. If this argument is missing, this method will return whether the table * is empty or not. * @returns Whether the table contains any records matching the given conditions. */ async hasAny(conditions?: Partial<DBRecord>): Promise<boolean> { try { await this.getOne(conditions); return true; } catch (error) { // Couldn't get a single record. return false; } } /** * Check whether the table has any record matching the given primary key. * * @param primaryKey Record primary key. * @returns Whether the table contains a record matching the given primary key. */ async hasAnyByPrimaryKey(primaryKey: PrimaryKey): Promise<boolean> { try { await this.getOneByPrimaryKey(primaryKey); return true; } catch (error) { // Couldn't get the record. return false; } } /** * Count records in table. * * @param conditions Matching conditions. * @returns Number of records matching the given conditions. */ count(conditions?: Partial<DBRecord>): Promise<number> { return this.database.countRecords(this.tableName, conditions); } /** * Insert a new record. * * @param record Database record. */ async insert(record: DBRecord): Promise<void> { await this.database.insertRecord(this.tableName, record); } /** * Update records matching the given conditions. * * @param updates Record updates. * @param conditions Matching conditions. If this argument is missing, all records will be updated. */ async update(updates: Partial<DBRecord>, conditions?: Partial<DBRecord>): Promise<void> { await this.database.updateRecords(this.tableName, updates, conditions); } /** * Update records matching the given conditions. * * This method should be used when it's necessary to apply complex conditions; the simple `update` * method should be favored otherwise for better performance. * * @param updates Record updates. * @param conditions Matching conditions in SQL and JavaScript. */ async updateWhere(updates: Partial<DBRecord>, conditions: CoreDatabaseConditions<DBRecord>): Promise<void> { await this.database.updateRecordsWhere(this.tableName, updates, conditions.sql, conditions.sqlParams); } /** * Delete records matching the given conditions. * * @param conditions Matching conditions. If this argument is missing, all records will be deleted. */ async delete(conditions?: Partial<DBRecord>): Promise<void> { conditions ? await this.database.deleteRecords(this.tableName, conditions) : await this.database.deleteRecords(this.tableName); } /** * Delete a single record identified by its primary key. * * @param primaryKey Record primary key. */ async deleteByPrimaryKey(primaryKey: PrimaryKey): Promise<void> { await this.database.deleteRecords(this.tableName, primaryKey); } /** * Get the primary key from a database record. * * @param record Database record. * @returns Primary key. */ protected getPrimaryKeyFromRecord(record: DBRecord): PrimaryKey { return this.primaryKeyColumns.reduce((primaryKey, column) => { primaryKey[column] = record[column]; return primaryKey; }, {} as Record<PrimaryKeyColumn, unknown>) as PrimaryKey; } /** * Serialize a primary key with a string representation. * * @param primaryKey Primary key. * @returns Serialized primary key. */ protected serializePrimaryKey(primaryKey: PrimaryKey): string { return Object.values(primaryKey).map(value => String(value)).join('-'); } /** * Check whether a given record matches the given conditions. * * @param record Database record. * @param conditions Matching conditions. * @returns Whether the record matches the conditions. */ protected recordMatches(record: DBRecord, conditions: Partial<DBRecord>): boolean { return !Object.entries(conditions).some(([column, value]) => record[column] !== value); } /** * Sort a list of records with the given order. This method mutates the input array. * * @param records Array of records to sort. * @param sorting Sorting conditions. * @returns Sorted array. This will be the same reference that was given as an argument. */ protected sortRecords(records: DBRecord[], sorting: CoreDatabaseSorting<DBRecord>): DBRecord[] { const columnsSorting = this.normalizedSorting(sorting); records.sort((a, b) => { for (const [column, direction] of columnsSorting) { const aValue = a[column]; const bValue = b[column]; if (aValue > bValue) { return direction === 'desc' ? -1 : 1; } if (aValue < bValue) { return direction === 'desc' ? 1 : -1; } } return 0; }); return records; } /** * Get a normalized array of sorting conditions. * * @param sorting Sorting conditions. * @returns Normalized sorting conditions. */ protected normalizedSorting(sorting: CoreDatabaseSorting<DBRecord>): [keyof DBRecord, 'asc' | 'desc'][] { const sortingArray = Array.isArray(sorting) ? sorting : [sorting]; return sortingArray.reduce((normalizedSorting, columnSorting) => { normalizedSorting.push( typeof columnSorting === 'object' ? [ Object.keys(columnSorting)[0] as keyof DBRecord, Object.values(columnSorting)[0] as 'asc' | 'desc', ] : [columnSorting, 'asc'], ); return normalizedSorting; }, [] as [keyof DBRecord, 'asc' | 'desc'][]); } } /** * Database configuration. */ export interface CoreDatabaseConfiguration { // This definition is augmented in subclasses. } /** * Database table listener. */ export interface CoreDatabaseTableListener { onDestroy?(): void; } /** * CoreDatabaseTable constructor. */ export type CoreDatabaseTableConstructor< DBRecord extends SQLiteDBRecordValues = SQLiteDBRecordValues, PrimaryKeyColumn extends keyof DBRecord = 'id', PrimaryKey extends GetDBRecordPrimaryKey<DBRecord, PrimaryKeyColumn> = GetDBRecordPrimaryKey<DBRecord, PrimaryKeyColumn> > = { new ( config: Partial<CoreDatabaseConfiguration>, database: SQLiteDB, tableName: string, primaryKeyColumns?: PrimaryKeyColumn[] ): CoreDatabaseTable<DBRecord, PrimaryKeyColumn, PrimaryKey>; }; /** * Infer primary key type from database record and primary key column types. */ export type GetDBRecordPrimaryKey<DBRecord extends SQLiteDBRecordValues, PrimaryKeyColumn extends keyof DBRecord> = { [column in PrimaryKeyColumn]: DBRecord[column]; }; /** * Reducer used to accumulate a value from multiple records both in SQL and JavaScript. * * Both operations should be equivalent. */ export type CoreDatabaseReducer<DBRecord, T> = { sql: string; js: (previousValue: T, record: DBRecord) => T; jsInitialValue: T; }; /** * Conditions to match database records both in SQL and JavaScript. * * Both conditions should be equivalent. */ export type CoreDatabaseConditions<DBRecord> = { sql: string; sqlParams?: SQLiteDBRecordValue[]; js: (record: DBRecord) => boolean; }; /** * Sorting conditions for a single column. * * This type will accept an object that defines sorting conditions for a single column, but not more. * For example, `{id: 'desc'}` and `{name: 'asc'}` would be acceptend values, but `{id: 'desc', name: 'asc'}` wouldn't. * * @see https://stackoverflow.com/questions/57571664/typescript-type-for-an-object-with-only-one-key-no-union-type-allowed-as-a-key */ export type CoreDatabaseColumnSorting<DBRecordColumn extends string | symbol | number> = { [Column in DBRecordColumn]: (Record<Column, 'asc' | 'desc'> & Partial<Record<Exclude<DBRecordColumn, Column>, never>>) extends infer ColumnSorting ? { [Column in keyof ColumnSorting]: ColumnSorting[Column] } : never; }[DBRecordColumn]; /** * Sorting conditions to apply to query results. * * Columns will be sorted in ascending order by default. */ export type CoreDatabaseSorting<DBRecord> = keyof DBRecord | CoreDatabaseColumnSorting<keyof DBRecord> | Array<keyof DBRecord | CoreDatabaseColumnSorting<keyof DBRecord>>; /** * Options to configure query results. */ export type CoreDatabaseQueryOptions<DBRecord> = { offset: number; limit: number; sorting: CoreDatabaseSorting<DBRecord>; };
the_stack
"use strict"; import { ASTNodeTypes, TxtNode, TxtParentNode } from "@textlint/ast-node-types"; import { Controller, traverse, VisitorOption } from "../src/"; const { parse } = require("@textlint/markdown-to-ast"); const Syntax = require("@textlint/markdown-to-ast").Syntax as typeof ASTNodeTypes; import { dump } from "./traverse-dump"; const assert = require("assert"); const enter = "enter"; const leave = "leave"; describe("txt-traverse", () => { describe("#traverse", () => { it("should traverse", () => { const AST: TxtParentNode = parse("# Header\n" + "Hello*world*"); const resultOfDump = dump(AST); const expected = [ [enter, Syntax.Document, null], // # Header [enter, Syntax.Header, Syntax.Document], [enter, Syntax.Str, Syntax.Header], [leave, Syntax.Str, Syntax.Header], [leave, Syntax.Header, Syntax.Document], // => Paragraph [enter, Syntax.Paragraph, Syntax.Document], [enter, Syntax.Str, Syntax.Paragraph], [leave, Syntax.Str, Syntax.Paragraph], // *world* [enter, Syntax.Emphasis, Syntax.Paragraph], [enter, Syntax.Str, Syntax.Emphasis], [leave, Syntax.Str, Syntax.Emphasis], [leave, Syntax.Emphasis, Syntax.Paragraph], // <= Paragraph [leave, Syntax.Paragraph, Syntax.Document], // End [leave, Syntax.Document, null] ]; assert.deepEqual(resultOfDump, expected); }); it("should traverse empty string", () => { const AST: TxtParentNode = parse(""); const resultOfDump = dump(AST); const expected = [ // Enter [enter, Syntax.Document, null], // Leave [leave, Syntax.Document, null] ]; assert.deepEqual(resultOfDump, expected); }); it("should traverse List", () => { const AST: TxtParentNode = parse(`- item 1 **Bold**`); const resultOfDump = dump(AST); const expected = [ ["enter", Syntax.Document, null], ["enter", Syntax.List, Syntax.Document], ["enter", Syntax.ListItem, Syntax.List], ["enter", Syntax.Paragraph, Syntax.ListItem], ["enter", Syntax.Str, Syntax.Paragraph], ["leave", Syntax.Str, Syntax.Paragraph], ["enter", Syntax.Strong, Syntax.Paragraph], ["enter", Syntax.Str, Syntax.Strong], ["leave", Syntax.Str, Syntax.Strong], ["leave", Syntax.Strong, Syntax.Paragraph], ["leave", Syntax.Paragraph, Syntax.ListItem], ["leave", Syntax.ListItem, Syntax.List], ["leave", Syntax.List, Syntax.Document], ["leave", Syntax.Document, null] ]; assert.deepEqual(resultOfDump, expected, JSON.stringify(resultOfDump)); }); it("should traverse Link", () => { const AST: TxtParentNode = parse(`[link](http://example.com)`); const resultOfDump = dump(AST); const expected = [ ["enter", "Document", null], ["enter", "Paragraph", "Document"], ["enter", "Link", "Paragraph"], ["enter", "Str", "Link"], ["leave", "Str", "Link"], ["leave", "Link", "Paragraph"], ["leave", "Paragraph", "Document"], ["leave", "Document", null] ]; assert.deepEqual(resultOfDump, expected, JSON.stringify(resultOfDump)); }); it("should traverse BlockQuote", () => { const AST: TxtParentNode = parse(`> **bold**`); const resultOfDump = dump(AST); const expected = [ ["enter", "Document", null], ["enter", "BlockQuote", "Document"], ["enter", "Paragraph", "BlockQuote"], ["enter", "Strong", "Paragraph"], ["enter", "Str", "Strong"], ["leave", "Str", "Strong"], ["leave", "Strong", "Paragraph"], ["leave", "Paragraph", "BlockQuote"], ["leave", "BlockQuote", "Document"], ["leave", "Document", null] ]; assert.deepEqual(resultOfDump, expected, JSON.stringify(resultOfDump)); }); it("should traverse Code", () => { const AST: TxtParentNode = parse("This is `code`"); const resultOfDump = dump(AST); const expected = [ ["enter", Syntax.Document, null], ["enter", Syntax.Paragraph, Syntax.Document], ["enter", Syntax.Str, Syntax.Paragraph], ["leave", Syntax.Str, Syntax.Paragraph], ["enter", Syntax.Code, Syntax.Paragraph], ["leave", Syntax.Code, Syntax.Paragraph], ["leave", Syntax.Paragraph, Syntax.Document], ["leave", Syntax.Document, null] ]; assert.deepEqual(resultOfDump, expected, JSON.stringify(resultOfDump)); }); it("should traverse CodeBlock", () => { const AST: TxtParentNode = parse("```" + "code block" + "```"); const resultOfDump = dump(AST); const expected = [ ["enter", Syntax.Document, null], ["enter", Syntax.Paragraph, Syntax.Document], ["enter", Syntax.Code, Syntax.Paragraph], ["leave", Syntax.Code, Syntax.Paragraph], ["leave", Syntax.Paragraph, Syntax.Document], ["leave", Syntax.Document, null] ]; assert.deepEqual(resultOfDump, expected, JSON.stringify(resultOfDump)); }); context("SKIP", () => { it("skip child nodes", () => { const AST: TxtParentNode = parse("# Header\n" + "Hello*world*"); const results: [string, string][] = []; traverse(AST, { enter(node: TxtNode) { results.push([enter, node.type]); if (node.type === Syntax.Header) { return VisitorOption.Skip; } return; }, leave(node) { results.push([leave, node.type]); } }); const expected = [ [enter, Syntax.Document], // # Header [enter, Syntax.Header], // SKIP [enter, Syntax.Str], // SKIP [leave, Syntax.Str], [leave, Syntax.Header], // => Paragraph [enter, Syntax.Paragraph], [enter, Syntax.Str], [leave, Syntax.Str], // *world* [enter, Syntax.Emphasis], [enter, Syntax.Str], [leave, Syntax.Str], [leave, Syntax.Emphasis], // <= Paragraph [leave, Syntax.Paragraph], // End [leave, Syntax.Document] ]; assert.deepEqual(results, expected); }); }); context("BREAK", () => { it("break child nodes", () => { const AST: TxtParentNode = parse("# Header\n" + "Hello*world*"); const results: [string, string][] = []; traverse(AST, { enter(node: TxtNode) { results.push([enter, node.type]); if (node.type === Syntax.Header) { return VisitorOption.Break; } return; }, leave(node) { results.push([leave, node.type]); } }); const expected = [ [enter, Syntax.Document], // # Header [enter, Syntax.Header] ]; assert.deepEqual(results, expected); }); }); }); describe("#parents", () => { it("should return parent nodes", () => { const AST = parse("Hello*world*"); const controller = new Controller(); let emParents: any[] = []; let documentParents: any[] = []; controller.traverse(AST, { enter(node: TxtNode) { if (node.type === Syntax.Document) { documentParents = controller.parents(); } if (node.type === Syntax.Emphasis) { emParents = controller.parents(); } } }); const emParentTypes = emParents.map((node) => { return node.type; }); const documentParentTypes = documentParents.map((node) => { return node.type; }); assert.deepEqual(emParentTypes, [Syntax.Document, Syntax.Paragraph]); assert.deepEqual(documentParentTypes, []); }); }); describe("#current", () => { it("should return current node", () => { const AST = parse("Hello*world*"); const controller = new Controller(); controller.traverse(AST, { enter(node) { assert.equal(controller.current()!.type, node.type); }, leave(node) { assert.equal(controller.current()!.type, node.type); } }); }); }); });
the_stack
import * as coreHttp from "@azure/core-http"; /** The result of a list request. */ export interface KeyListResult { /** The collection value. */ items?: Key[]; /** The URI that can be used to request the next set of paged results. */ nextLink?: string; } export interface Key { /** * The name of the key. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; } /** Azure App Configuration error object. */ export interface ErrorModel { /** The type of the error. */ type?: string; /** A brief summary of the error. */ title?: string; /** The name of the parameter that resulted in the error. */ name?: string; /** A detailed description of the error. */ detail?: string; /** The HTTP status code that the error maps to. */ status?: number; } /** The result of a list request. */ export interface KeyValueListResult { /** The collection value. */ items?: ConfigurationSetting[]; /** The URI that can be used to request the next set of paged results. */ nextLink?: string; } export interface ConfigurationSetting { /** The unique name of the key-value. */ key: string; /** The label of the key-value. */ label?: string; /** The content type of the key-value. */ contentType?: string; /** The value of the key-value. */ value?: string; /** The time the key-value was last modified. */ lastModified?: Date; /** Dictionary of <string> */ tags?: { [propertyName: string]: string }; /** Indicates whether or not this key-value is readonly. */ isReadOnly?: boolean; /** The entity-tag of the key-value. */ etag?: string; } /** The result of a list request. */ export interface LabelListResult { /** The collection value. */ items?: Label[]; /** The URI that can be used to request the next set of paged results. */ nextLink?: string; } export interface Label { /** * The name of the label. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; } /** Defines headers for GeneratedClient_getKeys operation. */ export interface GeneratedClientGetKeysHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_checkKeys operation. */ export interface GeneratedClientCheckKeysHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getKeyValues operation. */ export interface GeneratedClientGetKeyValuesHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_checkKeyValues operation. */ export interface GeneratedClientCheckKeyValuesHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getKeyValue operation. */ export interface GeneratedClientGetKeyValueHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; /** A UTC datetime that specifies the last time the resource was modified. */ lastModified?: string; } /** Defines headers for GeneratedClient_putKeyValue operation. */ export interface GeneratedClientPutKeyValueHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; } /** Defines headers for GeneratedClient_deleteKeyValue operation. */ export interface GeneratedClientDeleteKeyValueHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; } /** Defines headers for GeneratedClient_checkKeyValue operation. */ export interface GeneratedClientCheckKeyValueHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; /** A UTC datetime that specifies the last time the resource was modified. */ lastModified?: string; } /** Defines headers for GeneratedClient_getLabels operation. */ export interface GeneratedClientGetLabelsHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_checkLabels operation. */ export interface GeneratedClientCheckLabelsHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_putLock operation. */ export interface GeneratedClientPutLockHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; } /** Defines headers for GeneratedClient_deleteLock operation. */ export interface GeneratedClientDeleteLockHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; /** An identifier representing the returned state of the resource. */ eTag?: string; } /** Defines headers for GeneratedClient_getRevisions operation. */ export interface GeneratedClientGetRevisionsHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_checkRevisions operation. */ export interface GeneratedClientCheckRevisionsHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getKeysNext operation. */ export interface GeneratedClientGetKeysNextHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getKeyValuesNext operation. */ export interface GeneratedClientGetKeyValuesNextHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getLabelsNext operation. */ export interface GeneratedClientGetLabelsNextHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines headers for GeneratedClient_getRevisionsNext operation. */ export interface GeneratedClientGetRevisionsNextHeaders { /** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */ syncToken?: string; } /** Defines values for SettingFields. */ export type SettingFields = | "key" | "label" | "content_type" | "value" | "last_modified" | "tags" | "locked" | "etag"; /** Optional parameters. */ export interface GeneratedClientGetKeysOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned keys. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; } /** Contains response data for the getKeys operation. */ export type GeneratedClientGetKeysResponse = GeneratedClientGetKeysHeaders & KeyListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetKeysHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientCheckKeysOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned keys. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; } /** Contains response data for the checkKeys operation. */ export type GeneratedClientCheckKeysResponse = GeneratedClientCheckKeysHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientCheckKeysHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetKeyValuesOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the getKeyValues operation. */ export type GeneratedClientGetKeyValuesResponse = GeneratedClientGetKeyValuesHeaders & KeyValueListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyValueListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetKeyValuesHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientCheckKeyValuesOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the checkKeyValues operation. */ export type GeneratedClientCheckKeyValuesResponse = GeneratedClientCheckKeyValuesHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientCheckKeyValuesHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetKeyValueOptionalParams extends coreHttp.OperationOptions { /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** The label of the key-value to retrieve. */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; /** Used to perform an operation only if the targeted resource's etag does not match the value provided. */ ifNoneMatch?: string; } /** Contains response data for the getKeyValue operation. */ export type GeneratedClientGetKeyValueResponse = GeneratedClientGetKeyValueHeaders & ConfigurationSetting & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ConfigurationSetting; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetKeyValueHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientPutKeyValueOptionalParams extends coreHttp.OperationOptions { /** The label of the key-value to create. */ label?: string; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; /** Used to perform an operation only if the targeted resource's etag does not match the value provided. */ ifNoneMatch?: string; /** The key-value to create. */ entity?: ConfigurationSetting; } /** Contains response data for the putKeyValue operation. */ export type GeneratedClientPutKeyValueResponse = GeneratedClientPutKeyValueHeaders & ConfigurationSetting & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ConfigurationSetting; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientPutKeyValueHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientDeleteKeyValueOptionalParams extends coreHttp.OperationOptions { /** The label of the key-value to delete. */ label?: string; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; } /** Contains response data for the deleteKeyValue operation. */ export type GeneratedClientDeleteKeyValueResponse = GeneratedClientDeleteKeyValueHeaders & ConfigurationSetting & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ConfigurationSetting; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientDeleteKeyValueHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientCheckKeyValueOptionalParams extends coreHttp.OperationOptions { /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** The label of the key-value to retrieve. */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; /** Used to perform an operation only if the targeted resource's etag does not match the value provided. */ ifNoneMatch?: string; } /** Contains response data for the checkKeyValue operation. */ export type GeneratedClientCheckKeyValueResponse = GeneratedClientCheckKeyValueHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientCheckKeyValueHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetLabelsOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned labels. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** Used to select what fields are present in the returned resource(s). */ select?: string[]; } /** Contains response data for the getLabels operation. */ export type GeneratedClientGetLabelsResponse = GeneratedClientGetLabelsHeaders & LabelListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: LabelListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetLabelsHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientCheckLabelsOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned labels. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** Used to select what fields are present in the returned resource(s). */ select?: string[]; } /** Contains response data for the checkLabels operation. */ export type GeneratedClientCheckLabelsResponse = GeneratedClientCheckLabelsHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientCheckLabelsHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientPutLockOptionalParams extends coreHttp.OperationOptions { /** The label, if any, of the key-value to lock. */ label?: string; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; /** Used to perform an operation only if the targeted resource's etag does not match the value provided. */ ifNoneMatch?: string; } /** Contains response data for the putLock operation. */ export type GeneratedClientPutLockResponse = GeneratedClientPutLockHeaders & ConfigurationSetting & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ConfigurationSetting; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientPutLockHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientDeleteLockOptionalParams extends coreHttp.OperationOptions { /** The label, if any, of the key-value to unlock. */ label?: string; /** Used to perform an operation only if the targeted resource's etag matches the value provided. */ ifMatch?: string; /** Used to perform an operation only if the targeted resource's etag does not match the value provided. */ ifNoneMatch?: string; } /** Contains response data for the deleteLock operation. */ export type GeneratedClientDeleteLockResponse = GeneratedClientDeleteLockHeaders & ConfigurationSetting & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ConfigurationSetting; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientDeleteLockHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetRevisionsOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the getRevisions operation. */ export type GeneratedClientGetRevisionsResponse = GeneratedClientGetRevisionsHeaders & KeyValueListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyValueListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetRevisionsHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientCheckRevisionsOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the checkRevisions operation. */ export type GeneratedClientCheckRevisionsResponse = GeneratedClientCheckRevisionsHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientCheckRevisionsHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetKeysNextOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned keys. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; } /** Contains response data for the getKeysNext operation. */ export type GeneratedClientGetKeysNextResponse = GeneratedClientGetKeysNextHeaders & KeyListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetKeysNextHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetKeyValuesNextOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the getKeyValuesNext operation. */ export type GeneratedClientGetKeyValuesNextResponse = GeneratedClientGetKeyValuesNextHeaders & KeyValueListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyValueListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetKeyValuesNextHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetLabelsNextOptionalParams extends coreHttp.OperationOptions { /** A filter for the name of the returned labels. */ name?: string; /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** Used to select what fields are present in the returned resource(s). */ select?: string[]; } /** Contains response data for the getLabelsNext operation. */ export type GeneratedClientGetLabelsNextResponse = GeneratedClientGetLabelsNextHeaders & LabelListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: LabelListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetLabelsNextHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientGetRevisionsNextOptionalParams extends coreHttp.OperationOptions { /** Instructs the server to return elements that appear after the element referred to by the specified token. */ after?: string; /** Requests the server to respond with the state of the resource at the specified time. */ acceptDatetime?: string; /** A filter used to match keys. */ key?: string; /** A filter used to match labels */ label?: string; /** Used to select what fields are present in the returned resource(s). */ select?: SettingFields[]; } /** Contains response data for the getRevisionsNext operation. */ export type GeneratedClientGetRevisionsNextResponse = GeneratedClientGetRevisionsNextHeaders & KeyValueListResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: KeyValueListResult; /** The parsed HTTP response headers. */ parsedHeaders: GeneratedClientGetRevisionsNextHeaders; }; }; /** Optional parameters. */ export interface GeneratedClientOptionalParams extends coreHttp.ServiceClientOptions { /** Used to guarantee real-time consistency between requests. */ syncToken?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import Environment from '../Environment'; import { WorkerMessengerCommand } from '../libraries/WorkerMessenger'; import Path from '../models/Path'; import SdkEnvironment from '../managers/SdkEnvironment'; import Database from '../services/Database'; import { IntegrationKind } from '../models/IntegrationKind'; import { WindowEnvironmentKind } from '../models/WindowEnvironmentKind'; import NotImplementedError from '../errors/NotImplementedError'; import ProxyFrameHost from '../modules/frames/ProxyFrameHost'; import Log from '../libraries/Log'; import Event from '../Event'; import ProxyFrame from '../modules/frames/ProxyFrame'; import ServiceWorkerRegistrationError from "../errors/ServiceWorkerRegistrationError"; import OneSignalUtils from "../utils/OneSignalUtils"; import ServiceWorkerHelper, { ServiceWorkerActiveState, ServiceWorkerManagerConfig } from "../helpers/ServiceWorkerHelper"; import { ContextSWInterface } from '../models/ContextSW'; import { Utils } from "../context/shared/utils/Utils"; import { PageVisibilityRequest, PageVisibilityResponse } from "../models/Session"; import ServiceWorkerUtilHelper from "../helpers/page/ServiceWorkerUtilHelper"; export class ServiceWorkerManager { private context: ContextSWInterface; private readonly config: ServiceWorkerManagerConfig; constructor(context: ContextSWInterface, config: ServiceWorkerManagerConfig) { this.context = context; this.config = config; } // Gets details on the OneSignal service-worker (if any) public async getRegistration(): Promise<ServiceWorkerRegistration | null | undefined> { return await ServiceWorkerUtilHelper.getRegistration(this.config.registrationOptions.scope); } public async getActiveState(): Promise<ServiceWorkerActiveState> { /* Note: This method can only be called on a secure origin. On an insecure origin, it'll throw on getRegistration(). */ const integration = await SdkEnvironment.getIntegration(); if (integration === IntegrationKind.InsecureProxy) { /* Service workers are not accessible on insecure origins */ return ServiceWorkerActiveState.Indeterminate; } else if (integration === IntegrationKind.SecureProxy) { /* If the site setup is secure proxy, we're either on the top frame without access to the registration, or the child proxy frame that does have access to the registration. */ const env = SdkEnvironment.getWindowEnv(); switch (env) { case WindowEnvironmentKind.Host: case WindowEnvironmentKind.CustomIframe: /* Both these top-ish frames will need to ask the proxy frame to access the service worker registration */ const proxyFrameHost: ProxyFrameHost = OneSignal.proxyFrameHost; if (!proxyFrameHost) { /* On init, this function may be called. Return a null state for now */ return ServiceWorkerActiveState.Indeterminate; } else { return await proxyFrameHost.runCommand<ServiceWorkerActiveState>( OneSignal.POSTMAM_COMMANDS.SERVICE_WORKER_STATE ); } case WindowEnvironmentKind.OneSignalSubscriptionPopup: /* This is a top-level frame, so it can access the service worker registration */ break; case WindowEnvironmentKind.OneSignalSubscriptionModal: throw new NotImplementedError(); } } const workerRegistration = await this.context.serviceWorkerManager.getRegistration(); if (!workerRegistration) { return ServiceWorkerActiveState.None; } // We are now; 1. Getting the filename of the SW; 2. Checking if it is ours or a 3rd parties. const swFileName = ServiceWorkerManager.activeSwFileName(workerRegistration); const workerState = this.swActiveStateByFileName(swFileName); return workerState; } // Get the file name of the active ServiceWorker private static activeSwFileName(workerRegistration: ServiceWorkerRegistration): string | null { const serviceWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration); if (!serviceWorker) { return null; } const workerScriptPath = new URL(serviceWorker.scriptURL).pathname; const swFileName = new Path(workerScriptPath).getFileName(); // If the current service worker is Akamai's if (swFileName == "akam-sw.js") { // Check if its importing a ServiceWorker under it's "othersw" query param const searchParams = new URLSearchParams(new URL(serviceWorker.scriptURL).search); const importedSw = searchParams.get("othersw"); if (importedSw) { Log.debug("Found a ServiceWorker under Akamai's akam-sw.js?othersw=", importedSw); return new Path(new URL(importedSw).pathname).getFileName(); } } return swFileName; } // Check if the ServiceWorker file name is ours or a third party's private swActiveStateByFileName(fileName: string | null): ServiceWorkerActiveState { if (!fileName) return ServiceWorkerActiveState.None; if (fileName == this.config.workerAPath.getFileName()) return ServiceWorkerActiveState.WorkerA; if (fileName == this.config.workerBPath.getFileName()) return ServiceWorkerActiveState.WorkerB; return ServiceWorkerActiveState.ThirdParty; } public async getWorkerVersion(): Promise<number> { return new Promise<number>(async resolve => { if (OneSignalUtils.isUsingSubscriptionWorkaround()) { const proxyFrameHost: ProxyFrameHost = OneSignal.proxyFrameHost; if (!proxyFrameHost) { /* On init, this function may be called. Return a null state for now */ resolve(NaN); } else { const proxyWorkerVersion = await proxyFrameHost.runCommand<number>(OneSignal.POSTMAM_COMMANDS.GET_WORKER_VERSION); resolve(proxyWorkerVersion); } } else { this.context.workerMessenger.once(WorkerMessengerCommand.WorkerVersion, workerVersion => { resolve(workerVersion); }); this.context.workerMessenger.unicast(WorkerMessengerCommand.WorkerVersion); } }); } private async shouldInstallWorker(): Promise<boolean> { // 1. Does the browser support ServiceWorkers? if (!Environment.supportsServiceWorkers()) return false; // 2. Is OneSignal initialized? if (!OneSignal.config) return false; // 3. Will the service worker be installed on os.tc instead of the current domain? if (OneSignal.config.subdomain) { // No, if configured to use our subdomain (AKA HTTP setup) AND this is on their page (HTTP or HTTPS). // But since safari does not need subscription workaround, installing SW for session tracking. if ( OneSignal.environmentInfo.browserType !== "safari" && SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.Host ) { return false; } } // 4. Is a OneSignal ServiceWorker not installed now? // If not and notification permissions are enabled we should install. // This prevents an unnecessary install of the OneSignal worker which saves bandwidth const workerState = await this.getActiveState(); Log.debug("[shouldInstallWorker] workerState", workerState); if (workerState === ServiceWorkerActiveState.None || workerState === ServiceWorkerActiveState.ThirdParty) { const permission = await OneSignal.context.permissionManager.getNotificationPermission( OneSignal.config!.safariWebId ); const notificationsEnabled = permission === "granted"; if (notificationsEnabled) { Log.info("[shouldInstallWorker] Notification Permissions enabled, will install ServiceWorker"); } return notificationsEnabled; } // 5. We have a OneSignal ServiceWorker installed, but did the path or scope of the ServiceWorker change? if (await this.haveParamsChanged()) { return true; } // 6. We have a OneSignal ServiceWorker installed, is there an update? return this.workerNeedsUpdate(); } private async haveParamsChanged(): Promise<boolean> { // 1. No workerRegistration const workerRegistration = await this.context.serviceWorkerManager.getRegistration(); if (!workerRegistration) { Log.info( "[changedServiceWorkerParams] workerRegistration not found at scope", this.config.registrationOptions.scope ); return true; } // 2. Different scope const existingSwScope = new URL(workerRegistration.scope).pathname; const configuredSwScope = this.config.registrationOptions.scope; if (existingSwScope != configuredSwScope) { Log.info( "[changedServiceWorkerParams] ServiceWorker scope changing", { a_old: existingSwScope, b_new: configuredSwScope } ); return true; } // 3. Different href?, asking if (path + filename [A or B] + queryParams) is different const availableWorker = ServiceWorkerUtilHelper.getAvailableServiceWorker(workerRegistration); const serviceWorkerHrefs = ServiceWorkerHelper.getPossibleServiceWorkerHrefs( this.config, this.context.appConfig.appId ); // 3.1 If we can't get a scriptURL assume it is different if (!availableWorker?.scriptURL) { return true; } // 3.2 We don't care if the only differences is between OneSignal's A(Worker) vs B(WorkerUpdater) filename. if (serviceWorkerHrefs.indexOf(availableWorker.scriptURL) === -1) { Log.info( "[changedServiceWorkerParams] ServiceWorker href changing:", { a_old: availableWorker?.scriptURL, b_new: serviceWorkerHrefs } ); return true; } return false; } /** * Performs a service worker update by swapping out the current service worker * with a content-identical but differently named alternate service worker * file. */ private async workerNeedsUpdate(): Promise<boolean> { Log.info("[Service Worker Update] Checking service worker version..."); let workerVersion: number; try { workerVersion = await Utils.timeoutPromise(this.getWorkerVersion(), 2_000); } catch (e) { Log.info("[Service Worker Update] Worker did not reply to version query; assuming older version and updating."); return true; } if (workerVersion !== Environment.version()) { Log.info(`[Service Worker Update] Updating service worker from ${workerVersion} --> ${Environment.version()}.`); return true; } Log.info(`[Service Worker Update] Service worker version is current at ${workerVersion} (no update required).`); return false; } /** * Installs a newer version of the OneSignal service worker. * * We have a couple different models of installing service workers: * * a) Originally, we provided users with two worker files: * OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js. Two workers were * provided so each could be swapped with the other when the worker needed to * update. The contents of both workers were identical; only the filenames * were different, which is enough to update the worker. * * b) With AMP web push, users are to specify only the first worker file * OneSignalSDKWorker.js, with an app ID parameter ?appId=12345. AMP web push * is vendor agnostic and doesn't know about OneSignal, so all relevant * information has to be passed to the service worker, which is the only * vendor-specific file. So the service worker being installed is always * OneSignalSDKWorker.js?appId=12345 and never OneSignalSDKUpdaterWorker.js. * If AMP web push sees another worker like OneSignalSDKUpdaterWorker.js, or * even the same OneSignalSDKWorker.js without the app ID query parameter, the * user is considered unsubscribed. * * c) Due to b's restriction, we must always install * OneSignalSDKWorker.js?appId=xxx. We also have to appropriately handle * legacy cases: * * c-1) Where developers have OneSignalSDKWorker.js or * OneSignalSDKUpdaterWorker.js alternatingly installed * * c-2) Where developers running progressive web apps force-register * OneSignalSDKWorker.js * * Actually, users can customize the file names of Worker A / Worker B, but * it's up to them to be consistent with their naming. For AMP web push, users * can specify the full string to expect for the service worker. They can add * additional query parameters, but this must then stay consistent. * * Installation Procedure * ---------------------- * * Worker A is always installed. If Worker A is already installed, Worker B is * installed first, and then Worker A is installed again. This is necessary * because AMP web push requires Worker A to be installed for the user to be * considered subscribed. */ public async installWorker() { if (!await this.shouldInstallWorker()) { return; } await this.installAlternatingWorker(); if ((await this.getActiveState()) === ServiceWorkerActiveState.WorkerB) { // If the worker is Worker B, reinstall Worker A await this.installAlternatingWorker(); } await this.establishServiceWorkerChannel(); } public async establishServiceWorkerChannel() { Log.debug('establishServiceWorkerChannel'); const workerMessenger = this.context.workerMessenger; workerMessenger.off(); workerMessenger.on(WorkerMessengerCommand.NotificationDisplayed, data => { Log.debug(location.origin, 'Received notification display event from service worker.'); Event.trigger(OneSignal.EVENTS.NOTIFICATION_DISPLAYED, data); }); workerMessenger.on(WorkerMessengerCommand.NotificationClicked, async data => { let clickedListenerCallbackCount: number; if (SdkEnvironment.getWindowEnv() === WindowEnvironmentKind.OneSignalProxyFrame) { clickedListenerCallbackCount = await new Promise<number>(resolve => { const proxyFrame: ProxyFrame = OneSignal.proxyFrame; if (proxyFrame) { proxyFrame.messenger.message( OneSignal.POSTMAM_COMMANDS.GET_EVENT_LISTENER_COUNT, OneSignal.EVENTS.NOTIFICATION_CLICKED, (reply: any) => { const callbackCount: number = reply.data; resolve(callbackCount); } ); } }); } else clickedListenerCallbackCount = OneSignal.emitter.numberOfListeners(OneSignal.EVENTS.NOTIFICATION_CLICKED); if (clickedListenerCallbackCount === 0) { /* A site's page can be open but not listening to the notification.clicked event because it didn't call addListenerForNotificationOpened(). In this case, if there are no detected event listeners, we should save the event, instead of firing it without anybody receiving it. Or, since addListenerForNotificationOpened() only works once (you have to call it again each time), maybe it was only called once and the user isn't receiving the notification.clicked event for subsequent notifications on the same browser tab. Example: notificationClickHandlerMatch: 'origin', tab is clicked, event fires without anybody listening, calling addListenerForNotificationOpened() returns no results even though a notification was just clicked. */ Log.debug( 'notification.clicked event received, but no event listeners; storing event in IndexedDb for later retrieval.' ); /* For empty notifications without a URL, use the current document's URL */ let url = data.url; if (!data.url) { // Least likely to modify, since modifying this property changes the page's URL url = location.href; } await Database.put('NotificationOpened', { url: url, data: data, timestamp: Date.now() }); } else Event.trigger(OneSignal.EVENTS.NOTIFICATION_CLICKED, data); }); workerMessenger.on(WorkerMessengerCommand.RedirectPage, data => { Log.debug( `${SdkEnvironment.getWindowEnv().toString()} Picked up command.redirect to ${data}, forwarding to host page.` ); const proxyFrame: ProxyFrame = OneSignal.proxyFrame; if (proxyFrame) { proxyFrame.messenger.message(OneSignal.POSTMAM_COMMANDS.SERVICEWORKER_COMMAND_REDIRECT, data); } }); workerMessenger.on(WorkerMessengerCommand.NotificationDismissed, data => { Event.trigger(OneSignal.EVENTS.NOTIFICATION_DISMISSED, data); }); const isHttps = OneSignalUtils.isHttps(); const isSafari = OneSignalUtils.isSafari(); workerMessenger.on(WorkerMessengerCommand.AreYouVisible, (incomingPayload: PageVisibilityRequest) => { // For https sites in Chrome and Firefox service worker (SW) can get correct value directly. // For Safari, unfortunately, we need this messaging workaround because SW always gets false. if (isHttps && isSafari) { const payload: PageVisibilityResponse = { timestamp: incomingPayload.timestamp, focused: document.hasFocus(), }; workerMessenger.directPostMessageToSW(WorkerMessengerCommand.AreYouVisibleResponse, payload); } else { const httpPayload: PageVisibilityRequest = { timestamp: incomingPayload.timestamp }; const proxyFrame: ProxyFrame | undefined = OneSignal.proxyFrame; if (proxyFrame) { proxyFrame.messenger.message(OneSignal.POSTMAM_COMMANDS.ARE_YOU_VISIBLE_REQUEST, httpPayload); } } }); } /** * Installs the OneSignal service worker. * * Depending on the existing worker, the alternate swap worker may be * installed or, for 3rd party workers, the existing worker may be uninstalled * before installing ours. */ private async installAlternatingWorker() { const workerState = await this.getActiveState(); if (workerState === ServiceWorkerActiveState.ThirdParty) { Log.info(`[Service Worker Installation] 3rd party service worker detected.`); } const workerHref = ServiceWorkerHelper.getAlternatingServiceWorkerHref( workerState, this.config, this.context.appConfig.appId ); const scope = `${OneSignalUtils.getBaseUrl()}${this.config.registrationOptions.scope}`; Log.info(`[Service Worker Installation] Installing service worker ${workerHref} ${scope}.`); try { await navigator.serviceWorker.register(workerHref, { scope }); } catch (error) { Log.error(`[Service Worker Installation] Installing service worker failed ${error}`); // Try accessing the service worker path directly to find out what the problem is and report it to OneSignal api. // If we are inside the popup and service worker fails to register, it's not developer's fault. // No need to report it to the api then. const env = SdkEnvironment.getWindowEnv(); if (env === WindowEnvironmentKind.OneSignalSubscriptionPopup) throw error; const response = await fetch(workerHref); if (response.status === 403 || response.status === 404) throw new ServiceWorkerRegistrationError(response.status, response.statusText); throw error; } Log.debug(`[Service Worker Installation] Service worker installed.`); } }
the_stack
import {MessageDescriptor} from '@lingui/core' import * as Sentry from '@sentry/browser' import {ResultSegment} from 'components/ReportFlow/Analyse/ResultSegment' import ErrorMessage from 'components/ui/ErrorMessage' import {getReportPatch, Patch} from 'data/PATCHES' import {DependencyCascadeError, ModulesNotFoundError} from 'errors' import {Event} from 'event' import React from 'react' import {Report, Pull, Actor} from 'report' import toposort from 'toposort' import {extractErrorContext, isDefined, formatDuration} from 'utilities' import {Analyser, DisplayMode} from './Analyser' import {Dispatcher} from './Dispatcher' import {Injectable, MappedDependency} from './Injectable' import {Meta} from './Meta' export interface Result { i18n_id?: string handle: string name: string | MessageDescriptor mode: DisplayMode order: number markup: React.ReactNode } declare module 'event' { interface EventTypeRepository { complete: FieldsBase, } } export interface InitEvent { type: 'init' timestamp: number } export interface CompleteEvent { type: 'complete' timestamp: number } class Parser { // ----- // Properties // ----- readonly dispatcher: Dispatcher readonly patch: Patch readonly report: Report readonly pull: Pull readonly actor: Actor readonly meta: Meta container: Record<string, Injectable> = {} private executionOrder: string[] = [] _triggerModules: string[] = [] _moduleErrors: Record<string, Error/* | {toString(): string } */> = {} // Stored soonest-last for performance private eventDispatchQueue: Event[] = [] /** Get the unix epoch timestamp of the current state of the parser. */ get currentEpochTimestamp() { const start = this.pull.timestamp const end = start + this.pull.duration return Math.min(end, Math.max(start, this.dispatcher.timestamp)) } get currentDuration() { return this.currentEpochTimestamp - this.pull.timestamp } // ----- // Constructor // ----- constructor(opts: { meta: Meta, report: Report, pull: Pull, actor: Actor, dispatcher?: Dispatcher }) { this.dispatcher = opts.dispatcher ?? new Dispatcher() this.meta = opts.meta this.report = opts.report this.pull = opts.pull this.actor = opts.actor this.patch = new Patch( opts.report.edition, this.pull.timestamp / 1000, ) } // ----- // Module handling // ----- async configure() { const constructors = await this.loadModuleConstructors() // Build the values we need for the toposort const nodes = Object.keys(constructors) const edges: Array<[string, string]> = [] nodes.forEach(mod => constructors[mod].dependencies.forEach(dep => { edges.push([mod, this.getDepHandle(dep)]) })) // Sort modules to load dependencies first // Reverse is required to switch it into depencency order instead of sequence // This will naturally throw an error on cyclic deps this.executionOrder = toposort.array(nodes, edges).reverse() // Initialise the modules this.executionOrder.forEach(handle => { const injectable = new constructors[handle](this) this.container[handle] = injectable if (injectable instanceof Analyser) { injectable.initialise() } else { throw new Error(`Unhandled injectable type for initialisation: ${handle}`) } }) } private async loadModuleConstructors() { // If this throws, then there was probably a deploy between page load and this call. Tell them to refresh. let allCtors: ReadonlyArray<typeof Injectable> try { allCtors = await this.meta.getModules() } catch (error) { if (process.env.NODE_ENV === 'development') { throw error } throw new ModulesNotFoundError() } // Build a final contructor mapping. Modules later in the list with // the same handle with override earlier ones. const ctors: Record<string, typeof Injectable> = {} allCtors.forEach(ctor => { ctors[ctor.handle] = ctor }) return ctors } private getDepHandle = (dep: string | MappedDependency) => typeof dep === 'string' ? dep : dep.handle // ----- // Event handling // ----- parseEvents({events}: {events: Event[]}) { this._triggerModules = this.executionOrder.slice(0) for (const event of this.iterateXivaEvents(events)) { this.dispatchXivaEvent(event) } } private *iterateXivaEvents(events: Event[]): Iterable<Event> { const eventIterator = events[Symbol.iterator]() // Iterate the primary event source let result = eventIterator.next() while (!result.done) { const event = result.value // Check for, and yield, any queued events prior to the current timestamp // Using < rather than <= so that queued events execute after source events // of the same timestamp. Seems sane to me, but if it causes issue, change // the below to use <= instead - effectively weaving queue into source. const queue = this.eventDispatchQueue while (queue.length > 0 && queue[queue.length -1].timestamp < event.timestamp) { // Enforced by the while loop. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion yield queue.pop()! } // Yield the source event and prep for next iteration yield event result = eventIterator.next() } // Mark the end of the pull with a completion event yield { type: 'complete', timestamp: this.pull.timestamp + this.pull.duration, } } private dispatchXivaEvent(event: Event) { const issues = this.dispatcher.dispatch(event, this._triggerModules) for (const {handle, error} of issues) { this.captureError({ error, type: 'event', module: handle, event, }) this._setModuleError(handle, error) } } queueEvent(event: Event) { // If the event is in the past, noop. if (event.timestamp < this.currentEpochTimestamp) { if (process.env.NODE_ENV === 'development') { console.warn(`Attempted to queue an event in the past. Current timestamp: ${this.currentEpochTimestamp}. Event: ${JSON.stringify(event)}`) } return } // TODO: This logic is 1:1 with timestamp hook queue. Abstract? const index = this.eventDispatchQueue.findIndex( queueEvent => queueEvent.timestamp < event.timestamp, ) if (index === -1) { this.eventDispatchQueue.push(event) } else { this.eventDispatchQueue.splice(index, 0, event) } } private _setModuleError(mod: string, error: Error) { // Set the error for the current module const moduleIndex = this._triggerModules.indexOf(mod) if (moduleIndex !== -1) { this._triggerModules = this._triggerModules.slice(0) this._triggerModules.splice(moduleIndex, 1) } this._moduleErrors[mod] = error // Cascade via dependencies Object.keys(this.container).forEach(key => { const constructor = this.container[key].constructor as typeof Injectable if (constructor.dependencies.some(dep => this.getDepHandle(dep) === mod)) { this._setModuleError(key, new DependencyCascadeError({dependency: mod})) } }) } /** * Get error context for the named module and all of its dependencies. * @param mod The name of the module with the faulting code * @param source Either 'event' or 'output' * @param error The error that we're gathering context for * @param event The event that was being processed when the error occurred * @returns The resulting data along with an object containing errors that were encountered running getErrorContext methods. */ private _gatherErrorContext( mod: string, _source: 'event' | 'output', _error: Error, ): [Record<string, unknown>, Array<[string, Error]>] { const output: Record<string, unknown> = {} const errors: Array<[string, Error]> = [] const visited = new Set<string>() const crawler = (handle: string) => { visited.add(handle) const injectable = this.container[handle] const constructor = injectable.constructor as typeof Injectable // TODO: Should Injectable also contain rudimentary error logic? if (output[handle] === undefined) { output[handle] = extractErrorContext(injectable) } if (constructor && Array.isArray(constructor.dependencies)) { for (const dep of constructor.dependencies) { const handle = this.getDepHandle(dep) if (!visited.has(handle)) { crawler(handle) } } } } crawler(mod) return [output, errors] } // ----- // Results handling // ----- generateResults() { const results: Result[] = this.executionOrder.map(handle => { const injectable = this.container[handle] const resultMeta = this.getResultMeta(injectable) // If there's an error, override output handling to show it if (this._moduleErrors[handle]) { const error = this._moduleErrors[handle] return { ...resultMeta, markup: <ErrorMessage error={error} />, } } // Use the ErrorMessage component for errors in the output too (and sentry) let output: React.ReactNode = null try { output = this.getOutput(injectable) } catch (error) { this.captureError({ error, type: 'output', module: handle, }) // Also add the error to the results to be displayed. return { ...resultMeta, markup: <ErrorMessage error={error} />, } } if (output) { return ({ ...resultMeta, markup: output, }) } }).filter(isDefined) results.sort((a, b) => a.order - b.order) return results } private getResultMeta(injectable: Injectable): Result { if (injectable instanceof Analyser) { const constructor = injectable.constructor as typeof Analyser return { name: constructor.title, handle: constructor.handle, mode: constructor.displayMode, order: constructor.displayOrder, markup: null, } } const constructor = injectable.constructor as typeof Injectable throw new Error(`Unhandled injectable type for result meta: ${constructor.handle}`) } private getOutput(injectable: Injectable): React.ReactNode { if (injectable instanceof Analyser) { return injectable.output?.() } const constructor = injectable.constructor as typeof Injectable throw new Error(`Unhandled injectable type for output: ${constructor.handle}`) } // ----- // Error handling // ----- private captureError(opts: { error: Error, type: 'event' | 'output', module: string, event?: Event, }) { // Bypass error handling in dev if (process.env.NODE_ENV === 'development') { throw opts.error } // If the log should be analysed on a different branch, we'll probably be getting a bunch of errors - safe to ignore, as the logic will be fundamentally different. if (getReportPatch(this.report).branch) { return } // Gather info for Sentry const tags = { type: opts.type, job: this.actor.job, module: opts.module, } const extra: Record<string, unknown> = { source: this.report.meta.source, pull: this.pull.id, actor: this.actor.id, event: opts.event, } // Gather extra data for the error report. const [data, errors] = this._gatherErrorContext(opts.module, opts.type, opts.error) extra.modules = data for (const [m, err] of errors) { Sentry.withScope(scope => { scope.setTags({...tags, module: m}) scope.setExtras(extra) Sentry.captureException(err) }) } // Now that we have all the possible context, submit the // error to Sentry. Sentry.withScope(scope => { scope.setTags(tags) scope.setExtras(extra) Sentry.captureException(opts.error) }) } // ----- // Utilities // ----- formatEpochTimestamp(timestamp: number, secondPrecision?: number) { return this.formatDuration(timestamp - this.pull.timestamp, secondPrecision) } formatDuration(duration: number, secondPrecision?: number) { return formatDuration(duration, {secondPrecision, hideMinutesIfZero: true, showNegative: true}) } /** * Scroll to the specified module * @param handle - Handle of the module to scroll to */ scrollTo(handle: string) { const module = this.container[handle] ResultSegment.scrollIntoView((module.constructor as typeof Injectable).handle) } } export default Parser
the_stack
* @module OrbitGT */ //package orbitgt.pointcloud.format.opc; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { Coordinate } from "../../../spatial/geom/Coordinate"; import { AList } from "../../../system/collection/AList"; import { ALong } from "../../../system/runtime/ALong"; import { Message } from "../../../system/runtime/Message"; import { Strings } from "../../../system/runtime/Strings"; import { ContentLoader } from "../../../system/storage/ContentLoader"; import { FileStorage } from "../../../system/storage/FileStorage"; import { PointAttribute } from "../../model/PointAttribute"; import { AttributeReader } from "./AttributeReader"; import { ContainerFile } from "./ContainerFile"; import { ContainerFilePart } from "./ContainerFilePart"; import { DirectoryReader } from "./DirectoryReader"; import { DirectoryRecord } from "./DirectoryRecord"; import { EmbeddedAttributeReader } from "./EmbeddedAttributeReader"; import { FileRecord } from "./FileRecord"; import { GeometryReader } from "./GeometryReader"; /** * Class FileReader reads OPC files. * * @version 1.0 January 2014 */ /** @internal */ export class FileReader { /** The name of this module */ private static readonly MODULE: string = "FileReader"; /** The file storage */ private _fileStorage: FileStorage; /** The name of the file */ private _fileName: string; /** The container */ private _container: ContainerFile; /** The file record */ private _fileRecord: FileRecord; /** The directory readers (1 per level) */ private _directoryReaders: Array<DirectoryReader>; /** The geometry readers (1 per level) */ private _geometryReaders: Array<GeometryReader>; /** The attribute readers */ private _attributeReaders: Array<AttributeReader>; /** * Create a new reader. * @param fileName the name of the file. * @param container the container file. * @param fileRecord the file record. */ private constructor(fileStorage: FileStorage, fileName: string, container: ContainerFile, fileRecord: FileRecord) { /* Store the parameters */ this._fileStorage = fileStorage; this._fileName = fileName; this._container = container; this._fileRecord = fileRecord; /* Clear */ this._directoryReaders = null; this._geometryReaders = null; this._attributeReaders = null; } /** * Open a file. * @param fileName the name of the file. * @param lazyLoading avoid early loading to keep a low memory profile? * @return the reader. */ public static async openFile(fileStorage: FileStorage, fileName: string, lazyLoading: boolean): Promise<FileReader> { /* Open the container file */ let container: ContainerFile = await ContainerFile.read(fileStorage, fileName, "OPC3"); /* Read the file record */ let filePart: ContainerFilePart = container.getPart("file"); let fileRecord: FileRecord = await FileRecord.readNew(fileStorage, filePart.getFileAccess().getFileName(), filePart.getOffset(), filePart.getSize()); /* Create a reader */ let fileReader: FileReader = new FileReader(fileStorage, fileName, container, fileRecord); /* Open the reader */ fileReader = await fileReader.open(lazyLoading); /* Return the reader */ return fileReader; } /** * Open the reader. * @param lazyLoading avoid early loading to keep a low memory profile? * @return the reader. */ private async open(lazyLoading: boolean): Promise<FileReader> { /* Log */ Message.print(FileReader.MODULE, "Opening OPC with " + this._fileRecord.getLevelCount() + " levels (crs " + this._fileRecord.getCRS() + ", lazy? " + lazyLoading + ")"); Message.print(FileReader.MODULE, "Container has " + this._container.getPartCount() + " parts"); // for(ContainerFilePart part: this._container.getParts()) Message.print(MODULE,"Part '"+part.getName()+"'"); /* Define the content we are going to need (dozens of parts) */ Message.print(FileReader.MODULE, "Loading " + this._fileRecord.getLevelCount() + " levels and " + this._fileRecord.getAttributeCount() + " attributes"); let fileContents: ContentLoader = new ContentLoader(this._fileStorage, this._fileName); /* Only read the block list for the top levels? (to save memory) */ let prefetchLevelIndex: int32 = (this._fileRecord.getLevelCount() - 6); if (prefetchLevelIndex < 0) prefetchLevelIndex = 0; if (lazyLoading == false) prefetchLevelIndex = 0; Message.print(FileReader.MODULE, "Prefetching from level " + prefetchLevelIndex); /* Read the directory */ this._directoryReaders = new Array<DirectoryReader>(this._fileRecord.getLevelCount()); for (let i: number = 0; i < this._directoryReaders.length; i++) { let directoryReader: DirectoryReader = new DirectoryReader(this, i); let readBlockList: boolean = (i >= prefetchLevelIndex); directoryReader.loadData(readBlockList, fileContents); this._directoryReaders[i] = directoryReader; } /* Read the geometry */ this._geometryReaders = new Array<GeometryReader>(this._fileRecord.getLevelCount()); for (let i: number = 0; i < this._geometryReaders.length; i++) { let geometryReader: GeometryReader = new GeometryReader(this, i); geometryReader.loadData(fileContents); this._geometryReaders[i] = geometryReader; } /* Read the attributes */ this._attributeReaders = new Array<AttributeReader>(this._fileRecord.getAttributeCount()); for (let i: number = 0; i < this._fileRecord.getAttributeCount(); i++) { let attributeReader: EmbeddedAttributeReader = new EmbeddedAttributeReader(this._container, i, this._fileRecord.getLevelCount()); attributeReader.loadData(fileContents); this._attributeReaders[i] = attributeReader; } /* Load all data needed for the structures */ fileContents = await fileContents.load(); /* Read the directory */ for (let i: number = 0; i < this._directoryReaders.length; i++) { let readBlockList: boolean = (i >= prefetchLevelIndex); this._directoryReaders[i].loadData(readBlockList, fileContents); } /* Read the geometry */ for (let i: number = 0; i < this._geometryReaders.length; i++) { this._geometryReaders[i].loadData(fileContents); } /* Read the attributes */ for (let i: number = 0; i < this._fileRecord.getAttributeCount(); i++) { let attributeReader: EmbeddedAttributeReader = <EmbeddedAttributeReader><unknown>(this._attributeReaders[i]); attributeReader.loadData(fileContents); } /* Log file info */ Message.print(FileReader.MODULE, "OPC bounds are " + this._geometryReaders[0].getGeometryRecord().getBounds()); let tileGridSize0: Coordinate = this._geometryReaders[0].getGeometryRecord().getTileGrid().size; Message.print(FileReader.MODULE, "OPC level0 tile size is (" + tileGridSize0.x + "," + tileGridSize0.y + "," + tileGridSize0.z + ")"); let totalPointCount: ALong = ALong.ZERO; let totalTileCount: int32 = 0; let totalBlockCount: int32 = 0; for (let i: number = 0; i < this._fileRecord.getLevelCount(); i++) { let directoryRecord: DirectoryRecord = this._directoryReaders[i].getDirectoryRecord(); Message.print(FileReader.MODULE, "Level " + i + " has " + directoryRecord.getPointCount() + " points, " + directoryRecord.getTileCount() + " tiles, " + directoryRecord.getBlockCount() + " blocks"); totalPointCount = totalPointCount.add(directoryRecord.getPointCount()); totalTileCount += directoryRecord.getTileCount(); totalBlockCount += directoryRecord.getBlockCount(); } Message.print(FileReader.MODULE, "Pointcloud has " + totalPointCount + " points, " + totalTileCount + " tiles, " + totalBlockCount + " blocks"); /* Get the attributes */ Message.print(FileReader.MODULE, "Pointcloud has " + this._attributeReaders.length + " static attributes:"); for (let i: number = 0; i < this._attributeReaders.length; i++) { Message.print(FileReader.MODULE, "Attribute " + i + ": " + this._attributeReaders[i].getAttribute()); Message.print(FileReader.MODULE, " min: " + this._attributeReaders[i].getMinimumValue()); Message.print(FileReader.MODULE, " max: " + this._attributeReaders[i].getMaximumValue()); } /* Return the reader */ return this; } /** * Close the file. */ public close(): void { for (let attributeReader of this._attributeReaders) attributeReader.close(); if (this._container != null) this._container.close(true); this._container = null; } /** * Get the storage of the file. * @return the storage of the file. */ public getFileStorage(): FileStorage { return this._fileStorage; } /** * Get the name of the file. * @return the name of the file. */ public getFileName(): string { return this._fileName; } /** * Get the container file. * @return the container file. */ public getContainer(): ContainerFile { return this._container; } /** * Get the file record. * @return the file record. */ public getFileRecord(): FileRecord { return this._fileRecord; } /** * Get the number of resolution levels. * @return the number of resolution levels. */ public getLevelCount(): int32 { return this._fileRecord.getLevelCount(); } /** * Get a directory reader. * @param level the index of the level. * @return the directory reader. */ public getDirectoryReader(level: int32): DirectoryReader { return this._directoryReaders[level]; } /** * Get a geometry reader. * @param level the index of the level. * @return the geometry reader. */ public getGeometryReader(level: int32): GeometryReader { return this._geometryReaders[level]; } /** * Get the static attribute readers. * @return the static attribute readers. */ public getStaticAttributeReaders(): Array<AttributeReader> { return this._attributeReaders; } /** * Get the attribute readers. * @return the attribute readers. */ public getAttributeReaders(): Array<AttributeReader> { return this._attributeReaders; } /** * Get the attributes. * @return the attributes. */ public getAttributes(): Array<PointAttribute> { let list: Array<PointAttribute> = new Array<PointAttribute>(this._attributeReaders.length); for (let i: number = 0; i < this._attributeReaders.length; i++) list[i] = this._attributeReaders[i].getAttribute(); return list; } /** * Find an attribute reader. * @param attributeName the name of the attribute. * @return the attribute reader (null if not found). */ public findAttributeReader(attributeName: string): AttributeReader { /* Check the static attributes */ for (let attributeReader of this._attributeReaders) { if (Strings.equalsIgnoreCase(attributeReader.getAttribute().getName(), attributeName)) return attributeReader; } /* Not found */ return null; } }
the_stack
import * as probuf_minimal from "protobufjs/minimal"; const linearProto = require('./proto/linear.js'); var fs = require('fs'); import * as turfHelpers from '@turf/helpers'; import lineOffset from "@turf/line-offset"; import turfBbox from '@turf/bbox'; import turfBboxPolygon from '@turf/bbox-polygon'; import {quantileRankSorted} from "simple-statistics" const tileHierarchy:number = 6; const tileSource:string = 'osm'; const tileBuild:string = 'planet-180430'; export function getBinCountFromLength(referenceLength, binSize) { var numBins = Math.floor(referenceLength / binSize) + 1; return numBins; } export function getBinLength(referenceLength, binSize) { return referenceLength / getBinCountFromLength(referenceLength, binSize); } export function getBinPositionFromLocation(referenceLength, binSize, location) { var bin = Math.floor(location / getBinLength(referenceLength, binSize)) + 1; return bin; } export function generateBinId(referenceId, binCount, binPosition):string { var binId:string = referenceId + "{" + binCount; if(binPosition) binId = binId + ":" + binPosition; return binId; } export enum PeriodSize { OneSecond = 0, FiveSeconds = 1, TenSeconds = 2, FifteenSeconds = 3, ThirtySeconds = 4, OneMinute = 5, FiveMinutes = 6, TenMinutes = 7, FifteenMinutes = 8, ThirtyMinutes = 9, OneHour = 10, OneDay = 11, OneWeek = 12, OneMonth = 13, OneYear = 14 } class SharedStreetsBin { type:string; count:number; value:number; } class SharedStreetsLinearBins { referenceId:string; referenceLength:number; numberOfBins:number; bins:{}; constructor(referenceId:string, referenceLength:number, numberOfBins:number) { this.referenceId = referenceId; this.referenceLength = referenceLength; this.numberOfBins = numberOfBins; // defaults to one bin this.bins = {}; } getId():string { return generateBinId(this.referenceId, this.numberOfBins, null) } addBin(binPosition:number, type:string, count:number, value:number) { var bin = new SharedStreetsBin(); bin.type = type; bin.count = count; bin.value = value; this.bins[binPosition] = bin; } } export class WeeklySharedStreetsLinearBins extends SharedStreetsLinearBins { periodSize:PeriodSize; constructor(referenceId:string, referenceLength:number, numberOfBins:number, periodSize:PeriodSize) { super(referenceId, referenceLength, numberOfBins); this.periodSize = periodSize; } addPeriodBin(binPosition:number, period:number, type:string, count:number, value:number) { var bin = new SharedStreetsBin(); bin.type = type; bin.count = count; bin.value = value; if(!this.bins[binPosition]) { this.bins[binPosition] = {}; } this.bins[binPosition][period] = bin; } getFilteredBins(binPosition:number, typeFilter:string, periodFilter:number[]):SharedStreetsBin[] { var filteredBins = []; if(this.bins[binPosition]) { for(var period of Object.keys(this.bins[binPosition])) { if(periodFilter) { if(parseInt(period) < periodFilter[0] || parseInt(period) > periodFilter[1]) continue; } if(typeFilter) { if(typeFilter !== this.bins[binPosition][period].type) continue; } filteredBins.push(this.bins[binPosition][period]); } } return filteredBins; } getHourOfDaySummary(typeFilter:string) { var filteredBins = new Map<number,SharedStreetsBin[]>(); for(var binPosition of Object.keys(this.bins)) { for(var period of Object.keys(this.bins[binPosition])) { var hourOfDay = (parseInt(period) % 23); if(hourOfDay > 23) hourOfDay = hourOfDay - 23; if(hourOfDay <= 0) hourOfDay = hourOfDay + 23; if(typeFilter) { if(typeFilter !== this.bins[binPosition][period].type) continue; } if(!filteredBins[hourOfDay]) filteredBins[hourOfDay] = []; filteredBins[hourOfDay].push(this.bins[binPosition][period]); } } return filteredBins; } getValueForBin(binPosition:number, typeFilter:string, periodFilter:number[]) { var sum = 0; var filteredBins = this.getFilteredBins(binPosition, typeFilter, periodFilter); for(var bin of filteredBins) { sum = sum + bin.value; } return sum; } getCountForHoursOfDay(typeFilter) { var summary = this.getHourOfDaySummary(typeFilter); var hourOfDayCount = {}; for(var hourOfDay of Object.keys(summary)) { hourOfDayCount[hourOfDay] = 0; for(var bin of summary[hourOfDay]) { hourOfDayCount[hourOfDay] = hourOfDayCount[hourOfDay] + bin.count; } } return hourOfDayCount; } getCountForBin(binPosition:number, typeFilter:string, periodFilter:number[]) { var sum = 0; var filteredBins = this.getFilteredBins(binPosition, typeFilter, periodFilter); for(var bin of filteredBins) { sum = sum + bin.count; } return sum; } getCountForEdge(typeFilter:string, periodFilter:number[]) { var sum = 0; for(var binPosition = 0; binPosition < this.numberOfBins; binPosition++) { var filteredBins = this.getFilteredBins(binPosition, typeFilter, periodFilter); for(var bin of filteredBins) { sum = sum + bin.count; } } return sum; } } function processTile(reader):WeeklySharedStreetsLinearBins[] { var tileData = []; while (reader.pos < reader.len) { try { var result = linearProto.SharedStreetsWeeklyBinnedLinearReferences.decodeDelimited(reader).toJSON(); var linearBins = new WeeklySharedStreetsLinearBins(result.referenceId, result.referenceLength, result.numberOfBins, PeriodSize.OneHour); for(var i = 0; i < result.binPosition.length; i++) { var binPosition = result.binPosition[i]; for(var j = 0; j < result.binnedPeriodicData[i].bins.length; j++) { var period = result.binnedPeriodicData[i].periodOffset[j]; var bin = result.binnedPeriodicData[i].bins[j]; for(var h in bin.dataType) { linearBins.addPeriodBin(binPosition, period, bin.dataType[h], parseInt(bin.count[h]), parseInt(bin.value[h])) } } } tileData.push(linearBins); } catch(e) { console.log(e); } } return tileData; } class BinReferenceData { geometry; refLength; } //export async function query(event, cache:LocalCache, callback) { // var sourceTest = new RegExp("[a-z]{1,10}"); // var source = undefined; // if(sourceTest.test(event.pathParameters.source)) { // source = event.pathParameters.source; // if(source === "dc_pudo" && event.queryStringParameters.authKey != "c890c855-b968-4952-8c0a-64cc2ca446c3") { // callback(401, "Not authorized"); // return; // } // } // var weekTest = new RegExp("([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))"); // var week = undefined; // if(event.pathParameters.week === '2017-09-11' || weekTest.test(event.pathParameters.week)) // week = event.pathParameters.week; // var tileKeyTest = new RegExp("^[0-9\-]*$"); // var tileKeys = undefined; // if(tileKeyTest.test(event.pathParameters.tileKey)) { // tileKeys = []; // tileKeys.push(event.pathParameters.tileKey); // } // var typeFilter = null; // if(event.queryStringParameters.typeFilter) { // typeFilter = event.queryStringParameters.typeFilter; // } // var offset = 4; // if(event.queryStringParameters.offset) { // offset = parseInt(event.queryStringParameters.offset); // } // var normalizeByLength = false; // if(event.queryStringParameters.normalizeByLength) { // normalizeByLength = JSON.parse(event.queryStringParameters.normalizeByLength); // } // var periodFilter = null; // if(event.queryStringParameters.periodFilter) { // var periodFilterParts = event.queryStringParameters.periodFilter.split('-'); // periodFilter = []; // periodFilter[0] = parseInt(periodFilterParts[0]); // periodFilter[1] = parseInt(periodFilterParts[1]); // } // var bboxPolygon = undefined; // if(event.queryStringParameters && event.queryStringParameters.bounds) { // var bboxString = event.queryStringParameters.bounds; // var bboxParts = bboxString.split(",").map((s) => {return Number.parseFloat(s)}); // if(bboxParts.length == 4) { // var line = turfHelpers.lineString([[bboxParts[0],bboxParts[1]],[bboxParts[2],bboxParts[3]]]); // var bbox = turfBbox(line); // bboxPolygon = turfBboxPolygon(bbox); // } // tileKeys = getTileIdsForPolygon(bboxPolygon); // } // if(!source || !week || (!tileKeys && !bbox)) { // callback(400, "Invalid request"); // return; // } // var indexedGeoms = undefined; // var referenceIds = new Set<string>(); // var resultType = "bin"; // if(event.queryStringParameters && event.queryStringParameters.resultType) { // if(event.queryStringParameters.resultType === "bin") // resultType = "bin"; // else if(event.queryStringParameters.resultType === "summary") // resultType = "summary"; // else if(event.queryStringParameters.resultType === "rank") // resultType = "rank"; // else { // callback(400, "Invalid request"); // return; // } // } // if(event.queryStringParameters && event.queryStringParameters.referenceIds) { // var referenceIdStrings = event.queryStringParameters.referenceIds.split(","); // for(var referenceId of referenceIdStrings) { // referenceIds.add(referenceId); // } // } // else if(bboxPolygon) { // var geometries = await cache.within('geometries', bboxPolygon,true, tileSource, tileBuild, tileHierarchy); // for(var geometry of geometries) { // var geomData = cache.idIndex[geometry.properties.id]; // referenceIds.add(geomData.forwardReferenceId); // if(geomData.backReferenceId) // referenceIds.add(geomData.backReferenceId); // } // } // try { // var results; // if(resultType === "bin") { // results = {type:"FeatureCollection", features:[]}; // var selectedCount = 0; // for(var tileKey of tileKeys ) { // var data:Uint8Array = await downloadPath(source + '/b/' + week + '/' + tileKey + '.events.pbf'); // var reader = new probuf_minimal.Reader(data) // var tileData = processTile(reader); // for(var linearBin of tileData) { // if(!referenceIds.has(linearBin.referenceId)) // continue; // var refData = cache.idIndex[linearBin.referenceId]; // var geomData = cache.idIndex[refData.geometryId]; // var refLength = getReferenceLength(refData); // var binLength = refLength / linearBin.numberOfBins; // var direction = ReferenceDirection.FORWARD; // if(linearBin.referenceId === geomData.backReferenceId) // direction = ReferenceDirection.BACKWARD; // var binPoints = geometryToBins(geomData.feature, // linearBin.referenceId, // refLength, // linearBin.numberOfBins, // offset, // direction, // ReferenceSideOfStreet.RIGHT); // for(var binPoint of binPoints) { // var binPosition = binPoint.properties.bin; // if(typeFilter) // binPoint.properties['type'] = typeFilter; // var periodRange = periodFilter[1] - periodFilter[0]; // var value = linearBin.getValueForBin(binPosition, typeFilter, periodFilter); // var binCount = linearBin.getCountForBin(binPosition, typeFilter, periodFilter); // var binCountByLength = binCount / binLength; // var periodAverageCount = binCount / periodRange; // binPoint.properties['binLength'] = Math.round(binLength * 100) / 100; // binPoint.properties['periodAverageCount'] = Math.round(periodAverageCount * 100) / 100; // if(binCount > 10) // results.features.push(binPoint); // } // } // } // } // else if(resultType === "rank") { // results = {type:"FeatureCollection", features:[]}; // var unfilteredResults = {type:"FeatureCollection", features:[]}; // var edgeCounts:number[] = []; // var selectedCount = 0; // for(var tileKey of tileKeys ) { // var data:Uint8Array = await downloadPath(source + '/b/' + week + '/' + tileKey + '.events.pbf'); // var reader = new probuf_minimal.Reader(data) // var tileData = processTile(reader); // for(var linearBin of tileData) { // if(!referenceIds.has(linearBin.referenceId)) // continue; // var refData = cache.idIndex[linearBin.referenceId]; // var geomData = cache.idIndex[refData.geometryId]; // var refLength = getReferenceLength(refData); // var direction = ReferenceDirection.FORWARD; // if(linearBin.referenceId === geomData.backReferenceId) // direction = ReferenceDirection.BACKWARD; // var edgeTotal = linearBin.getCountForEdge(typeFilter, periodFilter); // if(normalizeByLength) // edgeTotal = edgeTotal / refLength; // edgeCounts.push(edgeTotal); // if(edgeTotal > 0) { // var curbGeom; // if(direction === ReferenceDirection.FORWARD) // curbGeom = lineOffset(geomData.feature, offset, {units: 'meters'}); // else { // var reverseGeom = geomUtils.reverseLineString(geomData.feature); // curbGeom = lineOffset(reverseGeom, offset, {units: 'meters'}); // } // curbGeom.properties.edgeTotal = edgeTotal; // unfilteredResults.features.push(curbGeom); // } // } // } // var sortedEdgeCounts = edgeCounts.sort(); // for(var edge of unfilteredResults.features) { // var rank:number = quantileRankSorted(sortedEdgeCounts, edge.properties.edgeTotal); // edge.properties['rank'] = Math.round(rank * 100) / 100; // delete edge.properties['edgeTotal']; // if(edge.properties['rank'] > 0.5) { // results.features.push(edge); // } // } // } // else if(resultType === "summary") { // results = {}; // var selectedCount = 0; // for(var tileKey of tileKeys ) { // var data:Uint8Array = await downloadPath(source + '/b/' + week + '/' + tileKey + '.events.pbf'); // var reader = new probuf_minimal.Reader(data) // var tileData = processTile(reader); // for(var linearBin of Object.values(tileData)) { // if(!referenceIds.has(linearBin.referenceId)) // continue; // var hourOfDayCount = linearBin.getCountForHoursOfDay(typeFilter); // for(var hourOfDay of Object.keys(hourOfDayCount)) { // if(!results[hourOfDay]) // results[hourOfDay] = 0; // results[hourOfDay] = results[hourOfDay] + hourOfDayCount[hourOfDay]; // } // } // } // for(var hourOfDay of Object.keys(results)) { // results[hourOfDay] = results[hourOfDay] / 8000; // } // } // callback(null, results); // } // catch(e) { // console.log(e) // callback(400, "Invalid request"); // return; // } // }
the_stack
// (Re-)generated by schema tool // >>>> DO NOT CHANGE THIS FILE! <<<< // Change the json schema instead import * as wasmlib from "wasmlib"; import * as sc from "./index"; export class CallOnChainCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncCallOnChain); params: sc.MutableCallOnChainParams = new sc.MutableCallOnChainParams(); results: sc.ImmutableCallOnChainResults = new sc.ImmutableCallOnChainResults(); } export class CallOnChainContext { params: sc.ImmutableCallOnChainParams = new sc.ImmutableCallOnChainParams(); results: sc.MutableCallOnChainResults = new sc.MutableCallOnChainResults(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class CheckContextFromFullEPCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncCheckContextFromFullEP); params: sc.MutableCheckContextFromFullEPParams = new sc.MutableCheckContextFromFullEPParams(); } export class CheckContextFromFullEPContext { params: sc.ImmutableCheckContextFromFullEPParams = new sc.ImmutableCheckContextFromFullEPParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class DoNothingCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncDoNothing); } export class DoNothingContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class GetMintedSupplyCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncGetMintedSupply); results: sc.ImmutableGetMintedSupplyResults = new sc.ImmutableGetMintedSupplyResults(); } export class GetMintedSupplyContext { results: sc.MutableGetMintedSupplyResults = new sc.MutableGetMintedSupplyResults(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class IncCounterCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncIncCounter); } export class IncCounterContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class InitCall { func: wasmlib.ScInitFunc = new wasmlib.ScInitFunc(sc.HScName, sc.HFuncInit); params: sc.MutableInitParams = new sc.MutableInitParams(); } export class InitContext { params: sc.ImmutableInitParams = new sc.ImmutableInitParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class PassTypesFullCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncPassTypesFull); params: sc.MutablePassTypesFullParams = new sc.MutablePassTypesFullParams(); } export class PassTypesFullContext { params: sc.ImmutablePassTypesFullParams = new sc.ImmutablePassTypesFullParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class RunRecursionCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncRunRecursion); params: sc.MutableRunRecursionParams = new sc.MutableRunRecursionParams(); results: sc.ImmutableRunRecursionResults = new sc.ImmutableRunRecursionResults(); } export class RunRecursionContext { params: sc.ImmutableRunRecursionParams = new sc.ImmutableRunRecursionParams(); results: sc.MutableRunRecursionResults = new sc.MutableRunRecursionResults(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class SendToAddressCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSendToAddress); params: sc.MutableSendToAddressParams = new sc.MutableSendToAddressParams(); } export class SendToAddressContext { params: sc.ImmutableSendToAddressParams = new sc.ImmutableSendToAddressParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class SetIntCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSetInt); params: sc.MutableSetIntParams = new sc.MutableSetIntParams(); } export class SetIntContext { params: sc.ImmutableSetIntParams = new sc.ImmutableSetIntParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class SpawnCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncSpawn); params: sc.MutableSpawnParams = new sc.MutableSpawnParams(); } export class SpawnContext { params: sc.ImmutableSpawnParams = new sc.ImmutableSpawnParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestBlockContext1Call { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestBlockContext1); } export class TestBlockContext1Context { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestBlockContext2Call { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestBlockContext2); } export class TestBlockContext2Context { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestCallPanicFullEPCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestCallPanicFullEP); } export class TestCallPanicFullEPContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestCallPanicViewEPFromFullCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestCallPanicViewEPFromFull); } export class TestCallPanicViewEPFromFullContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestChainOwnerIDFullCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestChainOwnerIDFull); results: sc.ImmutableTestChainOwnerIDFullResults = new sc.ImmutableTestChainOwnerIDFullResults(); } export class TestChainOwnerIDFullContext { results: sc.MutableTestChainOwnerIDFullResults = new sc.MutableTestChainOwnerIDFullResults(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestEventLogDeployCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestEventLogDeploy); } export class TestEventLogDeployContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestEventLogEventDataCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestEventLogEventData); } export class TestEventLogEventDataContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestEventLogGenericDataCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestEventLogGenericData); params: sc.MutableTestEventLogGenericDataParams = new sc.MutableTestEventLogGenericDataParams(); } export class TestEventLogGenericDataContext { params: sc.ImmutableTestEventLogGenericDataParams = new sc.ImmutableTestEventLogGenericDataParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class TestPanicFullEPCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncTestPanicFullEP); } export class TestPanicFullEPContext { state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class WithdrawToChainCall { func: wasmlib.ScFunc = new wasmlib.ScFunc(sc.HScName, sc.HFuncWithdrawToChain); params: sc.MutableWithdrawToChainParams = new sc.MutableWithdrawToChainParams(); } export class WithdrawToChainContext { params: sc.ImmutableWithdrawToChainParams = new sc.ImmutableWithdrawToChainParams(); state: sc.MutableTestCoreState = new sc.MutableTestCoreState(); } export class CheckContextFromViewEPCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewCheckContextFromViewEP); params: sc.MutableCheckContextFromViewEPParams = new sc.MutableCheckContextFromViewEPParams(); } export class CheckContextFromViewEPContext { params: sc.ImmutableCheckContextFromViewEPParams = new sc.ImmutableCheckContextFromViewEPParams(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class FibonacciCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewFibonacci); params: sc.MutableFibonacciParams = new sc.MutableFibonacciParams(); results: sc.ImmutableFibonacciResults = new sc.ImmutableFibonacciResults(); } export class FibonacciContext { params: sc.ImmutableFibonacciParams = new sc.ImmutableFibonacciParams(); results: sc.MutableFibonacciResults = new sc.MutableFibonacciResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class GetCounterCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetCounter); results: sc.ImmutableGetCounterResults = new sc.ImmutableGetCounterResults(); } export class GetCounterContext { results: sc.MutableGetCounterResults = new sc.MutableGetCounterResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class GetIntCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetInt); params: sc.MutableGetIntParams = new sc.MutableGetIntParams(); results: sc.ImmutableGetIntResults = new sc.ImmutableGetIntResults(); } export class GetIntContext { params: sc.ImmutableGetIntParams = new sc.ImmutableGetIntParams(); results: sc.MutableGetIntResults = new sc.MutableGetIntResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class GetStringValueCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewGetStringValue); params: sc.MutableGetStringValueParams = new sc.MutableGetStringValueParams(); results: sc.ImmutableGetStringValueResults = new sc.ImmutableGetStringValueResults(); } export class GetStringValueContext { params: sc.ImmutableGetStringValueParams = new sc.ImmutableGetStringValueParams(); results: sc.MutableGetStringValueResults = new sc.MutableGetStringValueResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class JustViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewJustView); } export class JustViewContext { state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class PassTypesViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewPassTypesView); params: sc.MutablePassTypesViewParams = new sc.MutablePassTypesViewParams(); } export class PassTypesViewContext { params: sc.ImmutablePassTypesViewParams = new sc.ImmutablePassTypesViewParams(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class TestCallPanicViewEPFromViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestCallPanicViewEPFromView); } export class TestCallPanicViewEPFromViewContext { state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class TestChainOwnerIDViewCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestChainOwnerIDView); results: sc.ImmutableTestChainOwnerIDViewResults = new sc.ImmutableTestChainOwnerIDViewResults(); } export class TestChainOwnerIDViewContext { results: sc.MutableTestChainOwnerIDViewResults = new sc.MutableTestChainOwnerIDViewResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class TestPanicViewEPCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestPanicViewEP); } export class TestPanicViewEPContext { state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class TestSandboxCallCall { func: wasmlib.ScView = new wasmlib.ScView(sc.HScName, sc.HViewTestSandboxCall); results: sc.ImmutableTestSandboxCallResults = new sc.ImmutableTestSandboxCallResults(); } export class TestSandboxCallContext { results: sc.MutableTestSandboxCallResults = new sc.MutableTestSandboxCallResults(); state: sc.ImmutableTestCoreState = new sc.ImmutableTestCoreState(); } export class ScFuncs { static callOnChain(ctx: wasmlib.ScFuncCallContext): CallOnChainCall { let f = new CallOnChainCall(); f.func.setPtrs(f.params, f.results); return f; } static checkContextFromFullEP(ctx: wasmlib.ScFuncCallContext): CheckContextFromFullEPCall { let f = new CheckContextFromFullEPCall(); f.func.setPtrs(f.params, null); return f; } static doNothing(ctx: wasmlib.ScFuncCallContext): DoNothingCall { return new DoNothingCall(); } static getMintedSupply(ctx: wasmlib.ScFuncCallContext): GetMintedSupplyCall { let f = new GetMintedSupplyCall(); f.func.setPtrs(null, f.results); return f; } static incCounter(ctx: wasmlib.ScFuncCallContext): IncCounterCall { return new IncCounterCall(); } static init(ctx: wasmlib.ScFuncCallContext): InitCall { let f = new InitCall(); f.func.setPtrs(f.params, null); return f; } static passTypesFull(ctx: wasmlib.ScFuncCallContext): PassTypesFullCall { let f = new PassTypesFullCall(); f.func.setPtrs(f.params, null); return f; } static runRecursion(ctx: wasmlib.ScFuncCallContext): RunRecursionCall { let f = new RunRecursionCall(); f.func.setPtrs(f.params, f.results); return f; } static sendToAddress(ctx: wasmlib.ScFuncCallContext): SendToAddressCall { let f = new SendToAddressCall(); f.func.setPtrs(f.params, null); return f; } static setInt(ctx: wasmlib.ScFuncCallContext): SetIntCall { let f = new SetIntCall(); f.func.setPtrs(f.params, null); return f; } static spawn(ctx: wasmlib.ScFuncCallContext): SpawnCall { let f = new SpawnCall(); f.func.setPtrs(f.params, null); return f; } static testBlockContext1(ctx: wasmlib.ScFuncCallContext): TestBlockContext1Call { return new TestBlockContext1Call(); } static testBlockContext2(ctx: wasmlib.ScFuncCallContext): TestBlockContext2Call { return new TestBlockContext2Call(); } static testCallPanicFullEP(ctx: wasmlib.ScFuncCallContext): TestCallPanicFullEPCall { return new TestCallPanicFullEPCall(); } static testCallPanicViewEPFromFull(ctx: wasmlib.ScFuncCallContext): TestCallPanicViewEPFromFullCall { return new TestCallPanicViewEPFromFullCall(); } static testChainOwnerIDFull(ctx: wasmlib.ScFuncCallContext): TestChainOwnerIDFullCall { let f = new TestChainOwnerIDFullCall(); f.func.setPtrs(null, f.results); return f; } static testEventLogDeploy(ctx: wasmlib.ScFuncCallContext): TestEventLogDeployCall { return new TestEventLogDeployCall(); } static testEventLogEventData(ctx: wasmlib.ScFuncCallContext): TestEventLogEventDataCall { return new TestEventLogEventDataCall(); } static testEventLogGenericData(ctx: wasmlib.ScFuncCallContext): TestEventLogGenericDataCall { let f = new TestEventLogGenericDataCall(); f.func.setPtrs(f.params, null); return f; } static testPanicFullEP(ctx: wasmlib.ScFuncCallContext): TestPanicFullEPCall { return new TestPanicFullEPCall(); } static withdrawToChain(ctx: wasmlib.ScFuncCallContext): WithdrawToChainCall { let f = new WithdrawToChainCall(); f.func.setPtrs(f.params, null); return f; } static checkContextFromViewEP(ctx: wasmlib.ScViewCallContext): CheckContextFromViewEPCall { let f = new CheckContextFromViewEPCall(); f.func.setPtrs(f.params, null); return f; } static fibonacci(ctx: wasmlib.ScViewCallContext): FibonacciCall { let f = new FibonacciCall(); f.func.setPtrs(f.params, f.results); return f; } static getCounter(ctx: wasmlib.ScViewCallContext): GetCounterCall { let f = new GetCounterCall(); f.func.setPtrs(null, f.results); return f; } static getInt(ctx: wasmlib.ScViewCallContext): GetIntCall { let f = new GetIntCall(); f.func.setPtrs(f.params, f.results); return f; } static getStringValue(ctx: wasmlib.ScViewCallContext): GetStringValueCall { let f = new GetStringValueCall(); f.func.setPtrs(f.params, f.results); return f; } static justView(ctx: wasmlib.ScViewCallContext): JustViewCall { return new JustViewCall(); } static passTypesView(ctx: wasmlib.ScViewCallContext): PassTypesViewCall { let f = new PassTypesViewCall(); f.func.setPtrs(f.params, null); return f; } static testCallPanicViewEPFromView(ctx: wasmlib.ScViewCallContext): TestCallPanicViewEPFromViewCall { return new TestCallPanicViewEPFromViewCall(); } static testChainOwnerIDView(ctx: wasmlib.ScViewCallContext): TestChainOwnerIDViewCall { let f = new TestChainOwnerIDViewCall(); f.func.setPtrs(null, f.results); return f; } static testPanicViewEP(ctx: wasmlib.ScViewCallContext): TestPanicViewEPCall { return new TestPanicViewEPCall(); } static testSandboxCall(ctx: wasmlib.ScViewCallContext): TestSandboxCallCall { let f = new TestSandboxCallCall(); f.func.setPtrs(null, f.results); return f; } }
the_stack
import './setup'; import { PLATFORM } from 'aurelia-pal'; import { validateScrolledState, scrollToEnd, waitForNextFrame, waitForFrames, scrollRepeat } from './utilities'; import { VirtualRepeat } from '../src/virtual-repeat'; import { StageComponent, ComponentTester } from 'aurelia-testing'; import { bootstrap } from 'aurelia-bootstrapper'; import { ITestAppInterface } from './interfaces'; PLATFORM.moduleName('src/virtual-repeat'); PLATFORM.moduleName('test/noop-value-converter'); PLATFORM.moduleName('src/infinite-scroll-next'); describe('vr-integration.instance-mutated.spec.ts', () => { let component: ComponentTester<VirtualRepeat>; let items: any[]; let resources: any[]; let itemHeight: number = 100; beforeEach(() => { component = undefined; items = createItems(1000); resources = [ 'src/virtual-repeat', 'test/noop-value-converter', ]; }); afterEach(() => { try { if (component) { component.dispose(); } } catch (ex) { console.log('Error disposing component'); console.error(ex); } }); runTestsCases( '.for="item of items"', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items">\${item}</div> </div>` ); runTestsCases( '.for="item of items | identity', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items | identity">\${item}</div> </div>`, [ class { static $resource = { type: 'valueConverter', name: 'identity', }; toView(val: any[]) { return val; } }, ] ); runTestsCases( '.for="item of items | cloneArray', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items | cloneArray">\${item}</div> </div>`, [ class { static $resource = { type: 'valueConverter', name: 'cloneArray', }; toView(val: any[]) { return Array.isArray(val) ? val.slice() : val; } }, ] ); runTestsCases( '.for="item of items | cloneArray | cloneArray | identity | cloneArray', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items | cloneArray | cloneArray | identity | cloneArray">\${item}</div> </div>`, [ class { static $resource = { type: 'valueConverter', name: 'identity', }; toView(val: any[]) { return val; } }, class { static $resource = { type: 'valueConverter', name: 'cloneArray', }; toView(val: any[]) { return Array.isArray(val) ? val.slice() : val; } }, ] ); runTestsCases( '.for="item of items & toView', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items & toView">\${item}</div> </div>` ); runTestsCases( '.for="item of items & twoWay', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items & twoWay">\${item}</div> </div>` ); runTestsCases( '.for="item of items | cloneArray | cloneArray | identity | cloneArray & toView', `<div id="scrollContainer" style="height: 500px; overflow-y: scroll;"> <div style="height: ${itemHeight}px;" virtual-repeat.for="item of items | cloneArray | cloneArray | identity | cloneArray & toView">\${item}</div> </div>`, [ class { static $resource = { type: 'valueConverter', name: 'identity', }; toView(val: any[]) { return val; } }, class { static $resource = { type: 'valueConverter', name: 'cloneArray', }; toView(val: any[]) { return Array.isArray(val) ? val.slice() : val; } }, ] ); function runTestsCases(title: string, $view: string, extraResources: any[] = []): void { it([ title, '\thandles splice when scrolled to end', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); viewModel.items.splice(995, 1, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); await waitForNextFrame(); validateScrolledState(virtualRepeat, viewModel, itemHeight); await scrollToEnd(virtualRepeat); let views = virtualRepeat.viewSlot.children; expect(views[views.length - 1].bindingContext.item).toBe(viewModel.items[viewModel.items.length - 1]); }); it([ title, '\thandles splice removing non-consecutive when scrolled to end', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items, getNextPage: function() { let itemLength = this.items.length; for (let i = 0; i < 100; ++i) { let itemNum = itemLength + i; this.items.push('item' + itemNum); } }, }); await scrollToEnd(virtualRepeat); for (let i = 0, ii = 100; i < ii; i++) { viewModel.items.splice(i + 1, 9); } await waitForNextFrame(); validateScrolledState(virtualRepeat, viewModel, itemHeight); await scrollToEnd(virtualRepeat); let views = virtualRepeat.viewSlot.children; expect(views[views.length - 1].bindingContext.item).toBe(viewModel.items[viewModel.items.length - 1]); }); it([ title, '\thandles splice non-consecutive when scrolled to end', '\t1000 items', '\t-- 12 max views', '\t-- splice to 840 (every 10 increment, remove 3 add i, 80 times)', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); for (let i = 0, ii = 80; i < ii; i++) { viewModel.items.splice(10 * i, 3, i as any); } expect(virtualRepeat.element.parentElement.scrollTop).toEqual(100 * 995, 'scrollTop 1'); await waitForNextFrame(); expect(virtualRepeat.element.parentElement.scrollHeight).toEqual(100 * 840, 'scrollHeight 2'); expect(virtualRepeat.element.parentElement.scrollTop).toEqual(100 * (840 - 5), 'scrollTop 2'); validateScrolledState(virtualRepeat, viewModel, itemHeight); await scrollToEnd(virtualRepeat); let views = virtualRepeat.viewSlot.children; expect(views[views.length - 1].bindingContext.item).toBe(viewModel.items[viewModel.items.length - 1]); }); it([ title, '\thandles splice removing many', '\t1000 items', '\t-- 12 max views', '\t-- splice to 24', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'virtualRepeat.viewsLength'); expect(virtualRepeat.element.parentElement.scrollTop).toEqual(100 * 995, 'scrollTop 1'); // more items remaining than viewslot capacity viewModel.items.splice(5, 1000 - virtualRepeat.minViewsRequired * 2 - 12); await waitForNextFrame(); expect(virtualRepeat.items.length).toEqual(24, 'virtualRepeat.items.length'); expect(virtualRepeat.element.parentElement.scrollHeight).toEqual(100 * 24, 'scrollHeight 2'); expect(virtualRepeat.element.parentElement.scrollTop).toEqual(100 * (24 - 5), 'scrollTop 2'); expect(virtualRepeat.$first).toBe(1000 - (1000 - virtualRepeat.minViewsRequired * 2), 'virtualRepeat._first 1'); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); it([ title, '\thandles splice removing more', '', ].join('\n'), async () => { // number of items remaining exactly as viewslot capacity const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); viewModel.items.splice(5, 1000 - virtualRepeat.minViewsRequired * 2); await waitForNextFrame(); expect(virtualRepeat.viewSlot.children.length).toBe(viewModel.items.length); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); // less items remaining than viewslot capacity it([ title, '\thandles splice removing even more', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); viewModel.items.splice(5, 1000 - virtualRepeat.minViewsRequired * 2 + 10); await waitForNextFrame(); expect(virtualRepeat.viewSlot.children.length).toBe(viewModel.items.length); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); it([ title, '\thandles splice removing non-consecutive', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); for (let i = 0, ii = 100; i < ii; i++) { viewModel.items.splice(i + 1, 9); } await waitForNextFrame(); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); it([ title, '\thandles splice non-consecutive', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); for (let i = 0, ii = 100; i < ii; i++) { viewModel.items.splice(3 * (i + 1), 3, i as any); } await waitForNextFrame(); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); it([ title, '\thandles splice removing many + add', '\t-- 1000 items', '\t-- 12 max views', '\t-- spliced to 12', '', ].join('\n'), async () => { let scrollCount = 0; const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); virtualRepeat.element.parentElement.onscroll = () => { scrollCount++; }; expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength'); scrollRepeat(virtualRepeat, 'end'); await waitForNextFrame(); expect(scrollCount).toBe(1, '@scroll 1'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * 995, 'anchor.parent.scrollTop 1'); expect(virtualRepeat.$first).toBe(988, 'repeat._first 1'); viewModel.items.splice(5, 990, {}, {}); const hasValueConverter = extraResources.length > 0; if (hasValueConverter) { await waitForFrames(2); expect(virtualRepeat.element.parentElement.scrollHeight).toBe(100 * 12, '| vc >> scroller.scrollHeight 2'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * (12 - 500 / 100), '| vc >> scroller.scrollTop 2'); expect(scrollCount).toBeGreaterThanOrEqual(2, '| vc >> @scroll 3'); expect(virtualRepeat.$first).toBe(0, '| vc >> repeat._first 2'); validateScrolledState(virtualRepeat, viewModel, itemHeight); } else { expect(scrollCount).toBe(1, '@scroll 2'); expect(virtualRepeat.$first).toBe(988, 'repeat._first 2'); expect(virtualRepeat.items.length).toBe(12, 'items.length 1'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * 995, 'scroller.scrollTop 1'); await waitForNextFrame(); expect(virtualRepeat.element.parentElement.scrollHeight).toBe(100 * 12, 'scroller.scrollHeight 2'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * (12 - 500 / 100), 'scroller.scrollTop 2'); expect(scrollCount).toBe(2, '@scroll 3'); expect(virtualRepeat.$first).toBe(0, 'repeat._first 3'); validateScrolledState(virtualRepeat, viewModel, itemHeight); } virtualRepeat.element.parentElement.onscroll = null; }); // this case is a bit differnet to above case, // where final result after mutation is 1 item over the max views count required // the previous test above has same number of items and views required it([ title, '\thandles splice removing many + add', '\t1000 items', '\t-- 12 max views', '\t-- spliced to 13', '', ].join('\n'), async () => { let scrollCount = 0; const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); virtualRepeat.element.parentElement.onscroll = () => { scrollCount++; }; expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength'); await scrollToEnd(virtualRepeat); expect(scrollCount).toBe(2, '@scroll 1'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * 995); viewModel.items.splice(5, 990, {}, {}, {}); const hasValueConverter = extraResources.length > 0; if (hasValueConverter) { await waitForFrames(2); expect(scrollCount).toBeGreaterThanOrEqual(2, '| vc >> @scroll 2'); expect(virtualRepeat.items.length).toBe(13, 'items.length 1'); expect(virtualRepeat.element.parentElement.scrollHeight).toBe(100 * 13, '| vc >> scroller.scrollHeight 1'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * (13 - 500 / 100), '| vc >> scroller.scrollTop 2'); expect(virtualRepeat.$first).toBe(13 - (5 + 1) * 2, '| vc >> repeat._first 1'); validateScrolledState(virtualRepeat, viewModel, itemHeight); } else { expect(scrollCount).toBe(2, '@scroll 2'); expect(virtualRepeat.items.length).toBe(13, 'items.length 1'); expect(virtualRepeat.element.parentElement.scrollTop).toBe(100 * 995); await waitForFrames(2); expect(scrollCount).toBe(3, '@scroll 3'); validateScrolledState(virtualRepeat, viewModel, itemHeight); } virtualRepeat.element.parentElement.onscroll = null; }); it([ title, '\thandles splice remove remaining + add', '', ].join('\n'), async () => { const { virtualRepeat, viewModel } = await bootstrapComponent({ items: items }); await scrollToEnd(virtualRepeat); viewModel.items.splice(5, 995, 'a', 'b', 'c'); await waitForNextFrame(); validateScrolledState(virtualRepeat, viewModel, itemHeight); }); async function bootstrapComponent<T>($viewModel?: ITestAppInterface<T>) { component = StageComponent .withResources([ ...resources, ...extraResources, ]) .inView($view) .boundTo($viewModel); await component.create(bootstrap); expect(document.body.contains(component.element)).toBe(true, 'repeat is setup in document'); return { virtualRepeat: component.viewModel, viewModel: $viewModel, component: component }; } } // interface IInstanceMutatedTestCase<T extends ITestAppInterface<any> = ITestAppInterface<any>> { // view: string | HTMLElement | HTMLElement[]; // viewModel: T; // extraResources?: any[]; // assert: (component: ComponentTester, repeat: VirtualRepeat, viewModel: T) => void; // } function createItems(amount: number, name: string = 'item') { return Array.from({ length: amount }, (_, index) => name + index); } });
the_stack
import {FieldNode, IntValueNode, SelectionNode} from "graphql/language"; import * as RDF from "@rdfjs/types"; import {Algebra, Util as AlgebraUtil} from "sparqlalgebrajs"; import {IConvertContext, SingularizeState} from "../IConvertContext"; import {IConvertSettings} from "../IConvertSettings"; import {Util} from "../Util"; import {INodeQuadContext, NodeHandlerAdapter} from "./NodeHandlerAdapter"; /** * A handler for converting GraphQL selection nodes to operations. */ export abstract class NodeHandlerSelectionAdapter<T extends SelectionNode> extends NodeHandlerAdapter<T> { constructor(targetKind: T['kind'], util: Util, settings: IConvertSettings) { super(targetKind, util, settings); } /** * Get the quad context of a field node that should be used for the whole definition node. * @param {FieldNode} field A field node. * @param {string} fieldLabel A field label. * @param {IConvertContext} convertContext A convert context. * @return {INodeQuadContext} The subject and optional auxiliary patterns. */ public getNodeQuadContextFieldNode(field: FieldNode, fieldLabel: string, convertContext: IConvertContext) : INodeQuadContext { return this.getNodeQuadContextSelectionSet(field.selectionSet, fieldLabel, { ...convertContext, path: this.util.appendFieldToPath(convertContext.path, fieldLabel), }); } /** * Convert a field node to an operation. * @param {IConvertContext} convertContext A convert context. * @param {FieldNode} fieldNode The field node to convert. * @param {boolean} pushTerminalVariables If terminal variables should be created. * @param {Pattern[]} auxiliaryPatterns Optional patterns that should be part of the BGP. * @return {Operation} The reslting operation. */ public fieldToOperation(convertContext: IConvertContext, fieldNode: FieldNode, pushTerminalVariables: boolean, auxiliaryPatterns?: Algebra.Pattern[]): Algebra.Operation { // If a deeper node is being selected, and if the current object should become the next subject const nesting = pushTerminalVariables; // Offset and limit can be changed using the magic arguments 'first' and 'offset'. let offset = 0; let limit; // Ignore 'id' and 'graph' fields, because we have processed them earlier in getNodeQuadContextSelectionSet. if (fieldNode.name.value === 'id' || fieldNode.name.value === 'graph') { pushTerminalVariables = false; // Validate all _-arguments, because even though they were handled before, // the validity of variables could not be checked, // as variablesMetaDict wasn't populated at that time yet. if (fieldNode.arguments) { for (const argument of fieldNode.arguments) { if (argument.name.value === '_') { this.util.handleNodeValue(argument.value, fieldNode.name.value, convertContext); } } } } // Determine the field label for variable naming, taking into account aliases const fieldLabel: string = this.util.getFieldLabel(fieldNode); // Handle the singular/plural scope if (convertContext.singularizeState === SingularizeState.SINGLE) { convertContext.singularizeVariables![this.util.nameToVariable(fieldLabel, convertContext).value] = true; } // Handle meta fields if (pushTerminalVariables) { const operationOverride = this.handleMetaField(convertContext, fieldLabel, auxiliaryPatterns); if (operationOverride) { return operationOverride; } } const operations: Algebra.Operation[] = auxiliaryPatterns ? [this.util.operationFactory.createBgp(auxiliaryPatterns)] : []; // Define subject and object const subjectOutput = this.getNodeQuadContextFieldNode(fieldNode, fieldLabel, convertContext); let object: RDF.Term = subjectOutput.subject || this.util.nameToVariable(fieldLabel, convertContext); let graph: RDF.Term = subjectOutput.graph || convertContext.graph; if (subjectOutput.auxiliaryPatterns) { operations.push(this.util.operationFactory.createBgp(subjectOutput.auxiliaryPatterns)); } // Check if there is a '_' argument // We do this before handling all other arguments so that the order of final triple patterns is sane. let createQuadPattern: boolean = true; let overrideObjectTerms: RDF.Term[] | null = null; if (pushTerminalVariables && fieldNode.arguments && fieldNode.arguments.length) { for (const argument of fieldNode.arguments) { if (argument.name.value === '_') { // '_'-arguments do not create an additional predicate link, but set the value directly. const valueOutput = this.util.handleNodeValue(argument.value, fieldNode.name.value, convertContext); overrideObjectTerms = valueOutput.terms; operations.push(this.util.operationFactory.createBgp( valueOutput.terms.map((term) => this.util.createQuadPattern( convertContext.subject, fieldNode.name, term, convertContext.graph, convertContext.context)), )); if (valueOutput.auxiliaryPatterns) { operations.push(this.util.operationFactory.createBgp(valueOutput.auxiliaryPatterns)); } pushTerminalVariables = false; break; } else if (argument.name.value === 'graph') { // 'graph'-arguments do not create an additional predicate link, but set the graph. const valueOutput = this.util.handleNodeValue(argument.value, fieldNode.name.value, convertContext); if (valueOutput.terms.length !== 1) { throw new Error(`Only single values can be set as graph, but got ${valueOutput.terms .length} at ${fieldNode.name.value}`); } graph = valueOutput.terms[0]; convertContext = { ...convertContext, graph }; if (valueOutput.auxiliaryPatterns) { operations.push(this.util.operationFactory.createBgp(valueOutput.auxiliaryPatterns)); } break; } else if (argument.name.value === 'alt') { // 'alt'-arguments do not create an additional predicate link, but create alt-property paths. let pathValue = argument.value; if (pathValue.kind !== 'ListValue') { pathValue = { kind: 'ListValue', values: [ pathValue ] }; } operations.push(this.util.createQuadPath(convertContext.subject, fieldNode.name, pathValue, object, convertContext.graph, convertContext.context)); createQuadPattern = false; break; } } } // Create at least a pattern for the parent node and the current path. if (pushTerminalVariables && createQuadPattern) { operations.push(this.util.operationFactory.createBgp([ this.util.createQuadPattern(convertContext.subject, fieldNode.name, object, convertContext.graph, convertContext.context), ])); } // Create patterns for the node's arguments if (fieldNode.arguments && fieldNode.arguments.length) { for (const argument of fieldNode.arguments) { if (argument.name.value === '_' || argument.name.value === 'graph' || argument.name.value === 'alt') { // no-op } else if (argument.name.value === 'first') { if (argument.value.kind !== 'IntValue') { throw new Error('Invalid value type for \'first\' argument: ' + argument.value.kind); } limit = parseInt((<IntValueNode> argument.value).value, 10); } else if (argument.name.value === 'offset') { if (argument.value.kind !== 'IntValue') { throw new Error('Invalid value type for \'offset\' argument: ' + argument.value.kind); } offset = parseInt((<IntValueNode> argument.value).value, 10); } else { const valueOutput = this.util.handleNodeValue(argument.value, argument.name.value, convertContext); operations.push(this.util.operationFactory.createBgp( valueOutput.terms.map((term) => this.util.createQuadPattern( object, argument.name, term, convertContext.graph, convertContext.context)), )); if (valueOutput.auxiliaryPatterns) { operations.push(this.util.operationFactory.createBgp(valueOutput.auxiliaryPatterns)); } } } } // Directives const directiveOutputs = this.getDirectiveOutputs(fieldNode.directives, fieldLabel, convertContext); if (!directiveOutputs) { return this.util.operationFactory.createBgp([]); } // Recursive call for nested selection sets let operation: Algebra.Operation = this.util.joinOperations(operations); if (fieldNode.selectionSet && fieldNode.selectionSet.selections.length) { // Override the object if needed if (overrideObjectTerms) { if (overrideObjectTerms.length !== 1) { throw new Error(`Only single values can be set as id, but got ${overrideObjectTerms .length} at ${fieldNode.name.value}`); } object = overrideObjectTerms[0]; } // Change path value when there was an alias on this node. const subConvertContext: IConvertContext = { ...convertContext, ...nesting ? { path: this.util.appendFieldToPath(convertContext.path, fieldLabel) } : {}, graph, subject: nesting ? object : convertContext.subject, }; // If the magic keyword 'totalCount' is present, include a count aggregator. let totalCount: boolean = false; const selections: ReadonlyArray<SelectionNode> = fieldNode.selectionSet.selections .filter((selection) => { if (selection.kind === 'Field' && selection.name.value === 'totalCount') { totalCount = true; return false; } return true; }); let joinedOperation = this.util.joinOperations(operations .concat(selections.map((selectionNode) => this.util.handleNode(selectionNode, subConvertContext)))); // Modify the operation if there was a count selection if (totalCount) { // Create to a count aggregation const expressionVariable = this.util.dataFactory.variable!('var' + this.settings.expressionVariableCounter!++); const countOverVariable: RDF.Variable = this.util.dataFactory .variable!(object.value + this.settings.variableDelimiter + 'totalCount'); const aggregator: Algebra.BoundAggregate = this.util.operationFactory.createBoundAggregate(expressionVariable, 'count', this.util.operationFactory.createTermExpression(object), false); const countProject = this.util.operationFactory.createProject( this.util.operationFactory.createExtend( this.util.operationFactory.createGroup(operation, [], [aggregator]), countOverVariable, this.util.operationFactory.createTermExpression(expressionVariable), ), [countOverVariable], ); convertContext.terminalVariables.push(countOverVariable); // If no other selections exist (next to totalCount), // then we just return the count operations as-is, // otherwise, we join the count operation with all other selections if (!selections.length) { joinedOperation = countProject; } else { joinedOperation = this.util.operationFactory.createJoin([ this.util.operationFactory.createProject(joinedOperation, []), countProject, ]); } } operation = joinedOperation; } else if (pushTerminalVariables && object.termType === 'Variable') { // If no nested selection sets exist, // consider the object variable as a terminal variable that should be selected. convertContext.terminalVariables.push(object); } // Wrap the operation in a slice if a 'first' or 'offset' argument was provided. if (offset || limit) { operation = this.util.operationFactory.createSlice(this.util.operationFactory.createProject( operation, AlgebraUtil.inScopeVariables(operation)), offset, limit); } // Override operation if needed return this.handleDirectiveOutputs(directiveOutputs, operation); } /** * Check if the given node is a meta field, for things like introspection. * If so, return a new operation for this, otherwise, null is returned. * @param {IConvertContext} convertContext A convert context. * @param {Term} subject The subject. * @param {string} fieldLabel The field label to convert. * @param {Pattern[]} auxiliaryPatterns Optional patterns that should be part of the BGP. * @return {Operation} An operation or undefined. */ public handleMetaField(convertContext: IConvertContext, fieldLabel: string, auxiliaryPatterns?: Algebra.Pattern[]): Algebra.Operation | undefined { // TODO: in the future, we should add support for GraphQL wide range of introspection features: // http://graphql.org/learn/introspection/ if (fieldLabel === '__typename') { const object: RDF.Variable = this.util.nameToVariable(fieldLabel, convertContext); convertContext.terminalVariables.push(object); return this.util.operationFactory.createBgp([ this.util.operationFactory.createPattern( convertContext.subject, this.util.dataFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.util.nameToVariable(fieldLabel, convertContext), convertContext.graph, ), ].concat(auxiliaryPatterns || [])); } } }
the_stack
import { AppendResult, END, ErrorType, EventData, EventStoreDBClient, excludeSystemEvents, jsonEvent, Position, ResolvedEvent, START, } from '@eventstore/db-client'; import { AppendToStreamOptions, GetStreamMetadataOptions, ReadStreamOptions, } from '@eventstore/db-client/dist/streams'; ////////////////////// // Event base types // ////////////////////// export type Event< EventType extends string = string, EventData extends object = object, EventMetadata extends object = object > = { type: EventType; data: EventData; metadata?: EventMetadata; }; type SnapshotMetadata = { snapshottedStreamRevision: string; }; type SnapshotEvent< EventType extends string = string, EventData extends object = object, EventMetadata extends SnapshotMetadata = SnapshotMetadata > = Event<EventType, EventData, EventMetadata> & { metadata: Readonly<EventMetadata>; }; //////////////////////// // Command base types // //////////////////////// export type Command< CommandType extends string = string, CommandData extends Record<string, unknown> = Record<string, unknown>, CommandMetadata extends Record<string, unknown> = Record<string, unknown> > = { readonly type: CommandType; readonly data: CommandData; metadata?: Readonly<CommandMetadata>; }; ///////////////////////// // Read events methods // ///////////////////////// type STREAM_NOT_FOUND = 'STREAM_NOT_FOUND'; async function readFromStream<StreamEvent extends Event>( eventStore: EventStoreDBClient, streamName: string, options?: ReadStreamOptions ): Promise<StreamEvent[] | STREAM_NOT_FOUND> { try { const events = await eventStore.readStream(streamName, options); return events .filter((resolvedEvent) => !!resolvedEvent.event) .map((resolvedEvent) => { return <StreamEvent>{ type: resolvedEvent.event!.type, data: resolvedEvent.event!.data, metadata: resolvedEvent.event!.metadata, }; }); } catch (error) { if (error.type == ErrorType.STREAM_NOT_FOUND) { return 'STREAM_NOT_FOUND'; } throw error; } } async function readLastEventFromStream<StreamEvent extends Event>( eventStore: EventStoreDBClient, streamName: string ): Promise<StreamEvent | STREAM_NOT_FOUND> { const events = await readFromStream<StreamEvent>(eventStore, streamName, { maxCount: 1, fromRevision: END, direction: 'backwards', }); if (events === 'STREAM_NOT_FOUND') { return 'STREAM_NOT_FOUND'; } return events[0]; } //////////////////////// // Snapshots Handling // //////////////////////// /// Read from the external snapshot async function readEventsFromExternalSnapshot< StreamEvent extends Event, SnapshotStreamEvent extends SnapshotEvent = StreamEvent & SnapshotEvent >( getLastSnapshot: ( streamName: string ) => Promise<SnapshotStreamEvent | undefined>, eventStore: EventStoreDBClient, streamName: string ): Promise<{ events: (StreamEvent | SnapshotStreamEvent)[]; lastSnapshotRevision?: bigint; }> { const snapshot = await getLastSnapshot(streamName); const lastSnapshotRevision = snapshot ? BigInt(snapshot.metadata.snapshottedStreamRevision) : undefined; const streamEvents = await readFromStream<StreamEvent>( eventStore, streamName, { fromRevision: lastSnapshotRevision, } ); if (streamEvents === 'STREAM_NOT_FOUND') throw 'STREAM_NOT_FOUND'; const events = snapshot ? [snapshot, ...streamEvents] : streamEvents; return { events, lastSnapshotRevision, }; } /// Read from the snapshot in the same stream function addSnapshotPrefix(streamName: string): string { return `snapshot-${streamName}`; } async function readSnapshotFromSeparateStream< SnapshotStreamEvent extends SnapshotEvent >( eventStore: EventStoreDBClient, streamName: string ): Promise<SnapshotStreamEvent | undefined> { const snapshotStreamName = addSnapshotPrefix(streamName); const snapshot = await readLastEventFromStream<SnapshotStreamEvent>( eventStore, snapshotStreamName ); return snapshot !== 'STREAM_NOT_FOUND' ? snapshot : undefined; } async function readStreamMetadata< StreamMetadata extends Record<string, unknown> >( eventStore: EventStoreDBClient, streamName: string, options?: GetStreamMetadataOptions ): Promise<StreamMetadata | undefined> { const result = await eventStore.getStreamMetadata<StreamMetadata>( streamName, options ); return result.metadata; } async function getLastSnapshotRevisionFromStreamMetadata( eventStore: EventStoreDBClient, streamName: string ): Promise<bigint | undefined> { const streamMetadata = await readStreamMetadata<SnapshotMetadata>( eventStore, streamName ); return streamMetadata ? BigInt(streamMetadata.snapshottedStreamRevision) : undefined; } async function readEventsFromSnapshotInTheSameStream< StreamEvent extends Event, SnapshotStreamEvent extends SnapshotEvent = SnapshotEvent & StreamEvent >( eventStore: EventStoreDBClient, streamName: string ): Promise<(StreamEvent | SnapshotStreamEvent)[]> { const lastSnapshotRevision = await getLastSnapshotRevisionFromStreamMetadata( eventStore, streamName ); const events = await readFromStream<StreamEvent>(eventStore, streamName, { fromRevision: lastSnapshotRevision, }); if (events === 'STREAM_NOT_FOUND') throw 'STREAM_NOT_FOUND'; return events; } export function appendToStream<StreamEvent extends Event>( client: EventStoreDBClient, streamName: string, events: StreamEvent[], options?: AppendToStreamOptions ): Promise<AppendResult> { const jsonEvents: EventData[] = events.map((event) => jsonEvent({ type: event.type, data: event.data as Record<string, unknown>, metadata: event.metadata, }) ); return client.appendToStream(streamName, jsonEvents, options); } /// Append to the external snapshot async function appendEventAndExternalSnapshot< State extends object = object, StreamEvent extends Event = Event, SnapshotStreamEvent extends SnapshotEvent = StreamEvent & SnapshotEvent >( tryBuildSnapshot: ( newEvent: StreamEvent, currentState: State, newStreamRevision: bigint ) => SnapshotStreamEvent | undefined, appendSnapshot: ( snapshot: SnapshotStreamEvent, streamName: string, lastSnapshotRevision?: bigint ) => Promise<AppendResult>, eventStore: EventStoreDBClient, streamName: string, newEvent: StreamEvent, currentState: State, lastSnapshotRevision?: bigint ): Promise<AppendResult> { const appendResult = await appendToStream(eventStore, streamName, [newEvent]); const snapshot = tryBuildSnapshot( newEvent, currentState, appendResult.nextExpectedRevision ); if (snapshot) { await appendSnapshot(snapshot, streamName, lastSnapshotRevision); } return appendResult; } function appendSnapshotToSeparateStream< SnapshotStreamEvent extends SnapshotEvent >( eventStore: EventStoreDBClient, snapshot: SnapshotStreamEvent, streamName: string, lastSnapshotRevision?: bigint ): Promise<AppendResult> { const snapshotStreamName = addSnapshotPrefix(streamName); // If there was no snapshot made before, // set snapshot stream metadata $maxCount to 1. // This will make sure that there is only one snapshot event. if (lastSnapshotRevision === undefined) { eventStore.setStreamMetadata(snapshotStreamName, { maxCount: 1 }); } return appendToStream(eventStore, snapshotStreamName, [snapshot]); } async function appendEventAndSnapshotToTheSameStream< State extends object = object, StreamEvent extends Event = Event >( tryBuildSnapshot: ( newEvent: StreamEvent, currentState: State ) => StreamEvent | undefined, eventStore: EventStoreDBClient, streamName: string, newEvent: StreamEvent, currentState: State ): Promise<AppendResult> { const snapshot = tryBuildSnapshot(newEvent, currentState); const eventsToAppend = snapshot ? [newEvent, snapshot] : [newEvent]; const appendResult = await appendToStream( eventStore, streamName, eventsToAppend ); const snapshottedStreamRevision = appendResult.nextExpectedRevision.toString(); await eventStore.setStreamMetadata<SnapshotMetadata>(streamName, { snapshottedStreamRevision, }); return appendResult; } export function aggregateStream<Aggregate, StreamEvent extends Event>( events: StreamEvent[], when: ( currentState: Partial<Aggregate>, event: StreamEvent ) => Partial<Aggregate>, check: (state: Partial<Aggregate>) => state is Aggregate ): Aggregate { const state = events.reduce<Partial<Aggregate>>(when, {}); return assertStateIsValid(state, check); } function applyEvent<Aggregate, StreamEvent extends Event>( currentState: Aggregate, event: StreamEvent, when: ( currentState: Partial<Aggregate>, event: StreamEvent ) => Partial<Aggregate>, check: (state: Partial<Aggregate>) => state is Aggregate ): Aggregate { return assertStateIsValid(when(currentState, event), check); } export function assertStateIsValid<Aggregate>( state: Partial<Aggregate>, check: (state: Partial<Aggregate>) => state is Aggregate ) { if (!check(state)) throw 'Aggregate state is not valid'; return state; } ///////////////////////// // Cash Register types // ///////////////////////// type CashRegister = { id: string; float: number; workstation: string; currentCashierId?: string; }; type CashRegisterSnapshoted = SnapshotEvent< 'cash-register-snapshoted', CashRegister >; type PlacedAtWorkStation = Event< 'placed-at-workstation', { cashRegisterId: string; workstation: string; placedAt: Date; } >; type ShiftStarted = Event< 'shift-started', { cashRegisterId: string; cashierId: string; startedAt: Date; } >; export type TransactionRegistered = Event< 'transaction-registered', { transactionId: string; cashRegisterId: string; amount: number; registeredAt: Date; } >; export type EndShift = Command< 'end-shift', { cashRegisterId: string; } >; export type ShiftEnded = Event< 'shift-finished', { cashRegisterId: string; finishedAt: Date; } >; type CashRegisterEvent = | PlacedAtWorkStation | ShiftStarted | TransactionRegistered | ShiftEnded | CashRegisterSnapshoted; function when( currentState: Partial<CashRegister>, event: CashRegisterEvent ): Partial<CashRegister> { switch (event.type) { case 'placed-at-workstation': return { id: event.data.cashRegisterId, workstation: event.data.workstation, float: 0, }; case 'shift-started': return { ...currentState, currentCashierId: event.data.cashierId, }; case 'transaction-registered': return { ...currentState, float: (currentState.float ?? 0) + event.data.amount, }; case 'shift-finished': return { ...currentState, currentCashierId: undefined, }; case 'cash-register-snapshoted': return { ...event.data, }; default: // Unexpected event type return { ...currentState, }; } } function isNotEmptyString(value: any): boolean { return typeof value === 'string' && value.length > 0; } function isPositiveNumber(value: any): boolean { return typeof value === 'number' && value >= 0; } export function isCashRegister( cashRegister: any ): cashRegister is CashRegister { return ( cashRegister !== undefined && isNotEmptyString(cashRegister.id) && isPositiveNumber(cashRegister.float) && isNotEmptyString(cashRegister.workstation) && (cashRegister.currentCashierId === undefined || isNotEmptyString(cashRegister.currentCashierId)) ); } function shouldDoSnapshot(newEvent: CashRegisterEvent): boolean { return newEvent.type === 'shift-finished'; } function buildCashRegisterSnapshot( currentState: CashRegister, newStreamRevision: bigint ): CashRegisterSnapshoted { return { type: 'cash-register-snapshoted', data: currentState, metadata: { snapshottedStreamRevision: newStreamRevision.toString() }, }; } function tryBuildCashRegisterSnapshot( newEvent: CashRegisterEvent, currentState: CashRegister, newStreamRevision: bigint ): CashRegisterSnapshoted | undefined { if (shouldDoSnapshot(newEvent)) return undefined; return buildCashRegisterSnapshot(currentState, newStreamRevision); } function tryBuildCashRegisterSnapshotNoMetadata( newEvent: CashRegisterEvent, currentState: CashRegister ): CashRegisterSnapshoted | undefined { // perform the check if snapshot should be made if (newEvent.type !== 'shift-finished') return undefined; return { type: 'cash-register-snapshoted', data: currentState, metadata: { snapshottedStreamRevision: undefined! }, }; } function endShift( events: CashRegisterEvent[], command: EndShift ): { newState: CashRegister; newEvent: ShiftEnded; } { const cashRegister = aggregateStream(events, when, isCashRegister); if (cashRegister.currentCashierId === undefined) { throw 'SHIFT_NOT_STARTED'; } const newEvent: ShiftEnded = { type: 'shift-finished', data: { cashRegisterId: cashRegister.id, finishedAt: new Date(), }, }; return { newState: applyEvent(cashRegister, newEvent, when, isCashRegister), newEvent, }; } /////////////////////////////////////////////////// // Handling with a snapshot in a separate stream // /////////////////////////////////////////////////// async function readCashRegisterEvents( eventStore: EventStoreDBClient, streamName: string ) { return readEventsFromExternalSnapshot<CashRegisterEvent>( (streamName) => readSnapshotFromSeparateStream(eventStore, streamName), eventStore, streamName ); } async function storeCashRegister( eventStore: EventStoreDBClient, streamName: string, newEvent: ShiftEnded, newState: CashRegister, lastSnapshotRevision?: bigint ) { return appendEventAndExternalSnapshot( tryBuildCashRegisterSnapshot, (snapshot, streamName, lastSnapshotRevision) => appendSnapshotToSeparateStream( eventStore, snapshot, streamName, lastSnapshotRevision ), eventStore, streamName, newEvent, newState, lastSnapshotRevision ); } export async function handleEndShift(command: EndShift): Promise<void> { const eventStore = EventStoreDBClient.connectionString( `esdb://localhost:2113?tls=false` ); const streamName = `cashregister-${command.data.cashRegisterId}`; // 1. Read events and snapshot from the separate stream const { events, lastSnapshotRevision } = await readCashRegisterEvents( eventStore, streamName ); // 2. Perform business logic handling the command const { newState, newEvent } = endShift(events, command); // 3. Append the new event and snapshot await storeCashRegister( eventStore, streamName, newEvent, newState, lastSnapshotRevision ); } ///////////////////////////////////////////////// // Handling with a snapshot in the same stream // ///////////////////////////////////////////////// async function readCashRegisterEventsSameSnapshotStream( eventStore: EventStoreDBClient, streamName: string ) { return readEventsFromSnapshotInTheSameStream<CashRegisterEvent>( eventStore, streamName ); } async function storeCashRegisterSameSnapshotStream( eventStore: EventStoreDBClient, streamName: string, newEvent: ShiftEnded, newState: CashRegister ) { return appendEventAndSnapshotToTheSameStream<CashRegister, CashRegisterEvent>( tryBuildCashRegisterSnapshotNoMetadata, eventStore, streamName, newEvent, newState ); } export async function handleEndShiftSameSnapshotStream( command: EndShift ): Promise<void> { const eventStore = EventStoreDBClient.connectionString( `esdb://localhost:2113?tls=false` ); const streamName = `cashregister-${command.data.cashRegisterId}`; // 1. Read events and snapshot from the separate stream const events = await readCashRegisterEventsSameSnapshotStream( eventStore, streamName ); // 2. Perform business logic handling the command const { newState, newEvent } = endShift(events, command); // 3. Append the new event and snapshot await storeCashRegisterSameSnapshotStream( eventStore, streamName, newEvent, newState ); } ////////////////////////////////// // Snapshotting on subscription // ////////////////////////////////// function loadCheckPoint(subscriptionId: string): Promise<Position | undefined> { throw new Error('Function not implemented.'); } function tryDoSnapshot( eventStore: EventStoreDBClient, resolvedEvent: ResolvedEvent ): Promise<void> { throw new Error('Function not implemented.'); } function storeCheckpoint( subscriptionId: string, position: Position ): Promise<void> { throw new Error('Function not implemented.'); } (async () => { // 1. Run asynchronous process waiting for the subscription to end. return new Promise<void>(async (resolve, reject) => { try { const subscriptionId = 'SnapshottingSubscriptionToAll'; const eventStore = EventStoreDBClient.connectionString( `esdb://localhost:2113?tls=false` ); // 2. Read checkpoint - last processed event position. const lastCheckpoint = await loadCheckPoint(subscriptionId); // 3. Subscribe to $all stream excluding system events eventStore .subscribeToAll({ fromPosition: lastCheckpoint ?? START, filter: excludeSystemEvents(), }) .on('data', async function (resolvedEvent) { // 4. Try to do snapshot await tryDoSnapshot(eventStore, resolvedEvent); // 5. Store new checkpoint await storeCheckpoint(subscriptionId, resolvedEvent.event!.position); }) .on('error', (error) => { // 6. End asynchronous process with error reject(error); }) // 7. When subscription finished end the process .on('close', () => resolve()) .on('end', () => resolve()); } catch (error) { reject(error); } }); })(); (async () => { // 1. Run asynchronous process waiting for the subscription to end. return new Promise<void>(async (resolve, reject) => { try { await subscribeToAll(reject, resolve); } catch (error) { reject(error); } }); })(); async function subscribeToAll( reject: (error: any) => void, resolve: () => void ) { const subscriptionId = 'SnapshottingSubscriptionToAll'; const eventStore = EventStoreDBClient.connectionString( `esdb://localhost:2113?tls=false` ); // 2. Read checkpoint - last processed event position. const lastCheckpoint = await loadCheckPoint(subscriptionId); // 3. Subscribe to $all stream excluding system events eventStore .subscribeToAll({ fromPosition: lastCheckpoint ?? START, filter: excludeSystemEvents(), }) .on('data', async function (resolvedEvent) { // 4. Try to do snapshot await tryDoSnapshot(eventStore, resolvedEvent); // 5. Store new checkpoint await storeCheckpoint(subscriptionId, resolvedEvent.event!.position); }) .on('error', (error) => { // 6. End asynchronous process with error reject(error); }) // 7. When subscription finished end the process .on('close', () => resolve()) .on('end', () => resolve()); } export async function snapshotCashRegisterOnSubscription( eventStore: EventStoreDBClient, resolvedEvent: ResolvedEvent ): Promise<void> { const event = { type: resolvedEvent.event!.type, data: resolvedEvent.event!.data, metadata: resolvedEvent.event!.metadata, } as CashRegisterEvent; // 1. Check if snapshot should be made if (!shouldDoSnapshot(event)) return; const streamName = resolvedEvent.event!.streamId; // 2. Read stream events const { events, lastSnapshotRevision } = await readCashRegisterEvents( eventStore, streamName ); // 3. Build the current stream state const currentState = aggregateStream(events, when, isCashRegister); // 4. Create snapshot const snapshot = buildCashRegisterSnapshot( currentState, resolvedEvent.event!.revision ); // 5. Append the new event and snapshot await appendSnapshotToSeparateStream( eventStore, snapshot, streamName, lastSnapshotRevision ); } // const snapshotTreshold = 10n; // function shouldDoSnapshot( // lastSnapshotRevision: bigint | undefined, // resolvedEvent: ResolvedEvent // ): boolean { // return ( // resolvedEvent.event && // resolvedEvent.event.revision - (lastSnapshotRevision ?? 0n) >= // snapshotTreshold // ); // } // const snapshotTreshold = 1000 * 60 * 3; // function shouldDoSnapshot( // lastSnapshotTimestamp: number | undefined, // resolvedEvent: ResolvedEvent // ): boolean { // return ( // resolvedEvent.event && // resolvedEvent.event.created - (lastSnapshotTimestamp ?? 0) >= // snapshotTreshold // ); // }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormUII_action_Information { interface tab__49A2FDF8_1814_49B5_BE5A_E7CAC97E0EE3_Sections { _B4B540BD_52D0_4CC9_BD42_16F4DDAEDDAD: DevKit.Controls.Section; } interface tab__80C2EEB7_9ADD_DE11_8E80_00155D289C61_Sections { _AAA1F133_9BDD_DE11_8E80_00155D289C61: DevKit.Controls.Section; } interface tab_General_Sections { Automation: DevKit.Controls.Section; General: DevKit.Controls.Section; URLNavigation: DevKit.Controls.Section; } interface tab__49A2FDF8_1814_49B5_BE5A_E7CAC97E0EE3 extends DevKit.Controls.ITab { Section: tab__49A2FDF8_1814_49B5_BE5A_E7CAC97E0EE3_Sections; } interface tab__80C2EEB7_9ADD_DE11_8E80_00155D289C61 extends DevKit.Controls.ITab { Section: tab__80C2EEB7_9ADD_DE11_8E80_00155D289C61_Sections; } interface tab_General extends DevKit.Controls.ITab { Section: tab_General_Sections; } interface Tabs { _49A2FDF8_1814_49B5_BE5A_E7CAC97E0EE3: tab__49A2FDF8_1814_49B5_BE5A_E7CAC97E0EE3; _80C2EEB7_9ADD_DE11_8E80_00155D289C61: tab__80C2EEB7_9ADD_DE11_8E80_00155D289C61; General: tab_General; } interface Body { Tab: Tabs; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Determines the mode of automation for this action */ UII_AutomationMode: DevKit.Controls.OptionSet; /** THis attribute captures the additional data in an xml format which can be used by the action. */ UII_ExtensionsXML: DevKit.Controls.String; /** Every Action should be mapped to a Hosted Application. The Hosted Application can have many Actions. */ uii_hostedapplicationid: DevKit.Controls.Lookup; /** sets whether this action is executed as default action for the hosted application */ UII_isDefault: DevKit.Controls.Boolean; /** Focus the application after the action is completed */ UII_isFocussedApplication: DevKit.Controls.Boolean; /** Run automation asynchronously to desktop thread */ UII_isRunModeAsynchronous: DevKit.Controls.Boolean; /** Specify the Method to be used to Navigate */ UII_Method: DevKit.Controls.OptionSet; /** The name of the custom entity. */ UII_name: DevKit.Controls.String; /** Speify the Query String needs to be added to the URL attribute. */ UII_QueryString: DevKit.Controls.String; /** Specify the URL to which the hosted web application should navigate. */ UII_URL: DevKit.Controls.String; /** Captures the Workflow Assembly Type. This is required when Workflow Automation mode is selected */ UII_WorkflowAssemblyType: DevKit.Controls.String; /** When Workflow XAML mode is selected for automation mode, this attribute captures the XAML code */ UII_WorkflowXAML: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Status of the UII Action */ statecode: DevKit.Controls.OptionSet; } } class FormUII_action_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form UII_action_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form UII_action_Information */ Body: DevKit.FormUII_action_Information.Body; /** The Footer section of form UII_action_Information */ Footer: DevKit.FormUII_action_Information.Footer; } class UII_actionApi { /** * DynamicsCrm.DevKit UII_actionApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Help text used to describe action parameters */ msdyusd_Help: DevKit.WebApi.StringValue; msdyusd_UnifiedServiceDeskCreated: DevKit.WebApi.BooleanValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the UII Action */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the UII Action */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier for entity instances */ UII_actionId: DevKit.WebApi.GuidValue; /** Determines the mode of automation for this action */ UII_AutomationMode: DevKit.WebApi.OptionSetValue; /** THis attribute captures the additional data in an xml format which can be used by the action. */ UII_ExtensionsXML: DevKit.WebApi.StringValue; /** Every Action should be mapped to a Hosted Application. The Hosted Application can have many Actions. */ uii_hostedapplicationid: DevKit.WebApi.LookupValue; /** sets whether this action is executed as default action for the hosted application */ UII_isDefault: DevKit.WebApi.BooleanValue; /** Focus the application after the action is completed */ UII_isFocussedApplication: DevKit.WebApi.BooleanValue; /** Run automation asynchronously to desktop thread */ UII_isRunModeAsynchronous: DevKit.WebApi.BooleanValue; /** Specify the Method to be used to Navigate */ UII_Method: DevKit.WebApi.OptionSetValue; /** The name of the custom entity. */ UII_name: DevKit.WebApi.StringValue; /** Speify the Query String needs to be added to the URL attribute. */ UII_QueryString: DevKit.WebApi.StringValue; /** Captures the Script path file which will be executed on selection of No Automation mode. */ UII_ScriptFilePathtoRun: DevKit.WebApi.StringValue; /** Specify the URL to which the hosted web application should navigate. */ UII_URL: DevKit.WebApi.StringValue; /** Captures the Workflow Assembly Type. This is required when Workflow Automation mode is selected */ UII_WorkflowAssemblyType: DevKit.WebApi.StringValue; /** When Workflow XAML mode is selected for automation mode, this attribute captures the Rules xml. */ UII_WorkflowRules: DevKit.WebApi.StringValue; /** When Workflow XAML mode is selected for automation mode, this attribute captures the XAML code */ UII_WorkflowXAML: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace UII_action { enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum UII_AutomationMode { /** 1 */ No_Automation, /** 2 */ Use_Workflow_Assembly, /** 3 */ Use_Workflow_XAML } enum UII_Method { /** 1 */ GET, /** 2 */ POST } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import stableStringify from 'fast-json-stable-stringify'; import { cached, CacheOption } from '../libs/cached_fn'; import { PrpcClientExt } from '../libs/prpc_client_ext'; import { parseProtoDuration } from '../libs/time_utils'; import { timeout } from '../libs/utils'; /* eslint-disable max-len */ /** * Manually coded type definition and classes for buildbucket services. * TODO(weiweilin): To be replaced by code generated version once we have one. * source: https://chromium.googlesource.com/infra/luci/luci-go/+/ea9b54c38d87a4813576454fac9ac868bab8d9bc/buildbucket/proto/builds_service.proto */ /* eslint-enable max-len */ export const TEST_PRESENTATION_KEY = '$recipe_engine/resultdb/test_presentation'; export const BLAMELIST_PIN_KEY = '$recipe_engine/milo/blamelist_pins'; export const BUILD_FIELD_MASK = 'id,builder,number,canceledBy,createTime,startTime,endTime,status,summaryMarkdown,input,output,steps,' + 'infra.swarming,infra.resultdb,tags,exe,schedulingTimeout,executionTimeout'; // Includes: id, builder, number, createTime, startTime, endTime, status, summaryMarkdown. export const SEARCH_BUILD_FIELD_MASK = 'builds.*.id,builds.*.builder,builds.*.number,builds.*.createTime,builds.*.startTime,builds.*.endTime,' + 'builds.*.status,builds.*.summaryMarkdown'; export const enum Trinary { Unset = 'UNSET', Yes = 'YES', No = 'NO', } export interface GetBuildRequest { readonly id?: string; readonly builder?: BuilderID; readonly buildNumber?: number; readonly fields?: string; } export interface SearchBuildsRequest { readonly predicate: BuildPredicate; readonly pageSize?: number; readonly pageToken?: string; readonly fields?: string; } export interface SearchBuildsResponse { readonly builds: readonly Build[]; readonly nextPageToken?: string; } export interface BuildPredicate { readonly builderId?: BuilderID; readonly status?: BuildStatus; readonly gerritChanges?: readonly GerritChange[]; readonly createdBy?: string; readonly tags?: readonly StringPair[]; readonly build?: BuildRange; readonly experiments?: readonly string[]; } export interface BuildRange { readonly startBuildId: string; readonly endBuildId: string; } export interface BuilderID { readonly project: string; readonly bucket: string; readonly builder: string; } export interface Timestamp { readonly seconds: number; readonly nanos: number; } export interface Build { readonly id: string; readonly builder: BuilderID; readonly number?: number; readonly canceledBy?: string; readonly createTime: string; readonly startTime?: string; readonly endTime?: string; readonly status: BuildStatus; readonly summaryMarkdown?: string; readonly input?: BuildInput; readonly output?: BuildOutput; readonly steps?: readonly Step[]; readonly infra?: BuildInfra; readonly tags: readonly StringPair[]; readonly exe: Executable; readonly schedulingTimeout?: string; readonly executionTimeout?: string; } // This is from https://chromium.googlesource.com/infra/luci/luci-go/+/HEAD/buildbucket/proto/common.proto#25 export enum BuildStatus { Scheduled = 'SCHEDULED', Started = 'STARTED', Success = 'SUCCESS', Failure = 'FAILURE', InfraFailure = 'INFRA_FAILURE', Canceled = 'CANCELED', } export interface TestPresentationConfig { /** * A list of keys that will be rendered as columns in the test results tab. * status is always the first column and name is always the last column (you * don't need to specify them). * * A key must be one of the following: * 1. 'v.{variant_key}': variant.def[variant_key] of the test variant (e.g. * v.gpu). */ column_keys?: string[]; /** * A list of keys that will be used for grouping test variants in the test * results tab. * * A key must be one of the following: * 1. 'status': status of the test variant. * 2. 'name': test_metadata.name of the test variant. * 3. 'v.{variant_key}': variant.def[variant_key] of the test variant (e.g. * v.gpu). * * Caveat: test variants with only expected results are not affected by this * setting and are always in their own group. */ grouping_keys?: string[]; } export interface BuildInput { readonly properties?: { [TEST_PRESENTATION_KEY]?: TestPresentationConfig; [key: string]: unknown; }; readonly gitilesCommit?: GitilesCommit; readonly gerritChanges?: GerritChange[]; readonly experiments?: string[]; } export interface GitilesCommit { readonly host: string; readonly project: string; readonly id?: string; readonly ref?: string; readonly position: number; } export interface GerritChange { readonly host: string; readonly project: string; readonly change: string; readonly patchset: string; } export interface BuildOutput { readonly properties?: { [TEST_PRESENTATION_KEY]?: TestPresentationConfig; [BLAMELIST_PIN_KEY]?: GitilesCommit[]; [key: string]: unknown; }; readonly gitilesCommit?: GitilesCommit; readonly logs: Log[]; } export interface Log { readonly name: string; readonly viewUrl: string; readonly url: string; } export interface Step { readonly name: string; readonly startTime?: string; readonly endTime?: string; readonly status: BuildStatus; readonly logs?: Log[]; readonly summaryMarkdown?: string; } export interface BuildInfra { readonly swarming: BuildInfraSwarming; readonly resultdb?: BuildInfraResultdb; } export interface BuildInfraBuildbucket { readonly serviceConfigRevision: string; readonly requestedProperties: { [key: string]: unknown }; readonly requestedDimensions: RequestedDimension[]; readonly hostname: string; } export interface RequestedDimension { readonly key: string; readonly value: string; readonly expiration: string; } export interface BuildInfraSwarming { readonly hostname: string; readonly taskId?: string; readonly parentRunId?: string; readonly taskServiceAccount: string; readonly priority: number; readonly taskDimensions: readonly RequestedDimension[]; readonly botDimensions?: StringPair[]; readonly caches: readonly BuildInfraSwarmingCacheEntry[]; } export interface StringPair { readonly key: string; readonly value: string; } export interface BuildInfraSwarmingCacheEntry { readonly name: string; readonly path: string; readonly waitForWarmCache: string; readonly envVar: string; } export interface BuildInfraLogDog { readonly hostname: string; readonly project: string; readonly prefix: string; } export interface BuildInfraRecipe { readonly cipdPackage: string; readonly name: string; } export interface BuildInfraResultdb { readonly hostname: string; readonly invocation?: string; } export interface Executable { readonly cipdPackage: string; readonly cipdVersion: string; readonly cmd: readonly string[]; } export interface PermittedActionsRequest { readonly resourceKind: string; readonly resourceIds: readonly string[]; } export interface PermittedActionsResponse { permitted: { [key: string]: ResourcePermissions }; validityDuration: string; } export interface ResourcePermissions { readonly actions?: readonly string[]; } export interface CancelBuildRequest { id: string; summaryMarkdown: string; fields?: string; } export interface ScheduleBuildRequest { requestId?: string; templateBuildId?: string; builder?: BuilderID; experiments?: { [key: string]: boolean }; properties?: {}; gitilesCommit?: GitilesCommit; gerritChanges?: GerritChange[]; tags?: StringPair[]; dimensions?: RequestedDimension[]; priority?: string; notify?: Notification; fields?: string; critical?: Trinary; exe?: Executable; swarming?: { parentRunId: string; }; } export class BuildsService { private static SERVICE = 'buildbucket.v2.Builds'; private readonly cachedCallFn: (opt: CacheOption, method: string, message: object) => Promise<unknown>; constructor(client: PrpcClientExt) { this.cachedCallFn = cached( (method: string, message: object) => client.call(BuildsService.SERVICE, method, message), { key: (method, message) => `${method}-${stableStringify(message)}`, } ); } async getBuild(req: GetBuildRequest, cacheOpt: CacheOption = {}) { return (await this.cachedCallFn(cacheOpt, 'GetBuild', req)) as Build; } async searchBuilds(req: SearchBuildsRequest, cacheOpt: CacheOption = {}) { return (await this.cachedCallFn(cacheOpt, 'SearchBuilds', req)) as SearchBuildsResponse; } async cancelBuild(req: CancelBuildRequest) { return (await this.cachedCallFn({ acceptCache: false, skipUpdate: true }, 'CancelBuild', req)) as Build; } async scheduleBuild(req: ScheduleBuildRequest) { return (await this.cachedCallFn({ acceptCache: false, skipUpdate: true }, 'ScheduleBuild', req)) as Build; } } export interface GetBuilderRequest { readonly id: BuilderID; } export interface Builder { descriptionHtml?: string; } export interface BuilderItem { readonly id: BuilderID; readonly config: Builder; } export class BuildersService { private static SERVICE = 'buildbucket.v2.Builders'; private readonly cachedCallFn: (opt: CacheOption, method: string, message: object) => Promise<unknown>; constructor(client: PrpcClientExt) { this.cachedCallFn = cached( (method: string, message: object) => client.call(BuildersService.SERVICE, method, message), { key: (method, message) => `${method}-${stableStringify(message)}` } ); } async getBuilder(req: GetBuilderRequest, cacheOpt: CacheOption = {}) { return (await this.cachedCallFn(cacheOpt, 'GetBuilder', req)) as BuilderItem; } } export class AccessService { private static SERVICE = 'access.Access'; private readonly cachedPermittedActionsFn: ( cacheOpt: CacheOption, req: PermittedActionsRequest ) => Promise<PermittedActionsResponse>; constructor(client: PrpcClientExt) { // TODO(weiweilin): access service can be unreliable. // Try to cache this in service worker or localStorage. this.cachedPermittedActionsFn = cached( async (req: PermittedActionsRequest) => { return (await client.call(AccessService.SERVICE, 'PermittedActions', req)) as PermittedActionsResponse; }, { key: (req) => stableStringify(req), expire: async (_req, resPromise) => { const res = await resPromise; await timeout(parseProtoDuration(res.validityDuration)); return; }, } ); } async permittedActions(req: PermittedActionsRequest, cacheOpt: CacheOption = {}) { return this.cachedPermittedActionsFn(cacheOpt, req); } }
the_stack
import expect from 'expect'; import { JID } from '../src'; // tslint:disable no-identical-functions no-duplicate-string // -------------------------------------------------------------------- // Test basic parsing // -------------------------------------------------------------------- test('Parse JID with only domain', () => { const res = JID.parse('example.com'); expect(res.local).toBe(''); expect(res.resource).toBe(''); expect(res.bare).toBe('example.com'); expect(res.full).toBe('example.com'); }); test('Parse JID with domain + resource', () => { const res = JID.parse('example.com/resource'); expect(res.domain).toBe('example.com'); expect(res.local).toBe(''); expect(res.resource).toBe('resource'); expect(res.bare).toBe('example.com'); expect(res.full).toBe('example.com/resource'); }); test('Parse JID with local + domain', () => { const res = JID.parse('local@example.com'); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe(''); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com'); }); test('Parse JID with local + domain + resource', () => { const res = JID.parse('local@example.com/resource'); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/resource'); }); test('Parse JID with resource including @', () => { const res = JID.parse('local@example.com/res@ource'); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('res@ource'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/res@ource'); }); test('Parse JID with resource including /', () => { const res = JID.parse('local@example.com/resource/2'); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource/2'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/resource/2'); }); // -------------------------------------------------------------------- // Test constructing from JID components // -------------------------------------------------------------------- test('Construct JID with only domain', () => { const res = JID.parse(JID.create({ domain: 'example.com' })); expect(res.domain).toBe('example.com'); expect(res.bare).toBe('example.com'); expect(res.full).toBe('example.com'); }); test('Construct JID with domain + resource', () => { const res = JID.parse(JID.create({ domain: 'example.com', resource: 'resource' })); expect(res.domain).toBe('example.com'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('example.com'); expect(res.full).toBe('example.com/resource'); }); test('Construct JID with local + domain', () => { const res = JID.parse(JID.create({ local: 'local', domain: 'example.com' })); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com'); }); test('Construct JID with local + domain + resource', () => { const res = JID.parse( JID.create({ local: 'local', domain: 'example.com', resource: 'resource' }) ); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/resource'); }); test('Construct JID with resource including @', () => { const res = JID.parse( JID.create({ local: 'local', domain: 'example.com', resource: 'res@ource' }) ); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('res@ource'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/res@ource'); }); test('Construct JID with resource including /', () => { const res = JID.parse( JID.create({ local: 'local', domain: 'example.com', resource: 'resource/2' }) ); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource/2'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/resource/2'); }); // -------------------------------------------------------------------- // Test edge case valid forms // -------------------------------------------------------------------- test('Valid: IPv4 domain', () => { const res = JID.parse('local@127.0.0.1/resource'); expect(res.domain).toBe('127.0.0.1'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@127.0.0.1'); expect(res.full).toBe('local@127.0.0.1/resource'); }); test('Valid: IPv6 domain', () => { const res = JID.parse('local@[::1]/resource'); expect(res.domain).toBe('[::1]'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@[::1]'); expect(res.full).toBe('local@[::1]/resource'); }); test('Valid: ACE domain', () => { const res = JID.parse('local@xn--bcher-kva.ch/resource'); expect(res.domain).toBe('bücher.ch'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@bücher.ch'); expect(res.full).toBe('local@bücher.ch/resource'); }); test('Valid: domain includes trailing .', () => { const res = JID.parse('local@example.com./resource'); expect(res.domain).toBe('example.com'); expect(res.local).toBe('local'); expect(res.resource).toBe('resource'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/resource'); }); // -------------------------------------------------------------------- // Test JID prepping // -------------------------------------------------------------------- test('Prep: Lowercase', () => { const res = JID.parse('LOCAL@EXAMPLE.com/RESOURCE'); expect(res.local).toBe('local'); expect(res.domain).toBe('example.com'); expect(res.resource).toBe('RESOURCE'); expect(res.bare).toBe('local@example.com'); expect(res.full).toBe('local@example.com/RESOURCE'); }); // -------------------------------------------------------------------- // Test escaping/unescaping // -------------------------------------------------------------------- test('Escape: No starting/ending \\20', () => { const res = JID.parse(JID.create({ local: ' test ', domain: 'example.com' })); expect(res.local).toBe('test'); }); test('Escape: Existing escape sequences', () => { const res = JID.parse( JID.create({ local: 'test\\20\\22\\26\\27\\2f\\3a\\3c\\3e\\40', domain: 'example.com' }) ); expect(res.local).toBe('test\\20\\22\\26\\27\\2f\\3a\\3c\\3e\\40'); expect(res.bare).toBe('test\\5c20\\5c22\\5c26\\5c27\\5c2f\\5c3a\\5c3c\\5c3e\\5c40@example.com'); }); test('Escape: Existing escape sequence \\5c', () => { const res = JID.parse(JID.create({ local: 'test\\5c', domain: 'example.com' })); expect(res.local).toBe('test\\5c'); expect(res.bare).toBe('test\\5c5c@example.com'); }); test('Escape: Non-escape sequence \\32\\', () => { const res = JID.parse(JID.create({ local: 'test\\32\\', domain: 'example.com' })); expect(res.local).toBe('test\\32\\'); expect(res.bare).toBe('test\\32\\@example.com'); }); test('Escape: Escaped characters', () => { const res = JID.parse(JID.create({ local: 'testing @\\\'"?:&<>', domain: 'example.com' })); expect(res.bare).toBe('testing\\20\\40\\\\27\\22?\\3a\\26\\3c\\3e@example.com'); expect(res.local).toBe('testing @\\\'"?:&<>'); }); test('Unescape: Non-escape sequence', () => { const res = JID.parse('test\\32@example.com'); expect(res.local).toBe('test\\32'); expect(res.bare).toBe('test\\32@example.com'); }); test('Unescape: Escaped characters', () => { const res = JID.parse('testing\\20\\40\\5c\\27\\22?\\3a\\26\\3c\\3e@example.com'); expect(res.bare).toBe('testing\\20\\40\\5c\\27\\22?\\3a\\26\\3c\\3e@example.com'); expect(res.local).toBe('testing @\\\'"?:&<>'); }); // -------------------------------------------------------------------- // Test equality // -------------------------------------------------------------------- test('Equal: Full JID', () => { const jid1 = 'local@example.com/resource'; const jid2 = 'LOcAL@EXample.COM/resource'; expect(JID.equal(jid1, jid2)).toBeTruthy(); }); test('Equal: Bare JID', () => { const jid1 = 'local@example.com/resource1'; const jid2 = 'LOcAL@EXample.COM/resource2'; expect(JID.equalBare(jid1, jid2)).toBeTruthy(); }); // -------------------------------------------------------------------- // Test JID utilities // -------------------------------------------------------------------- test('isBare', () => { const jid1 = 'local@example.com'; const jid2 = 'local@example.com/resource'; expect(JID.isBare(jid1)).toBeTruthy(); expect(JID.isBare(jid2)).toBeFalsy(); }); test('isFull', () => { const jid1 = 'local@example.com/resource'; const jid2 = 'local@example.com'; expect(JID.isFull(jid1)).toBeTruthy(); expect(JID.isFull(jid2)).toBeFalsy(); }); // -------------------------------------------------------------------- // Test URIs // -------------------------------------------------------------------- test('Wrong protocol', () => { expect(() => JID.parseURI('https://example.com')).toThrow(); }); test('JID only', () => { const res = JID.parseURI('xmpp:user@example.com'); expect(res.jid).toBe('user@example.com'); }); test('JID with resource', () => { const res = JID.parseURI('xmpp:user@example.com/resource'); expect(res.jid).toBe('user@example.com/resource'); }); test('JID with only domain', () => { const res = JID.parseURI('xmpp:example.com'); expect(res.jid).toBe('example.com'); }); test('JID with domain and resource', () => { const res = JID.parseURI('xmpp:example.com/resource'); expect(res.jid).toBe('example.com/resource'); }); test('URI with query command, no parameters', () => { const res = JID.parseURI('xmpp:user@example.com/resource?message'); expect(res.jid).toBe('user@example.com/resource'); expect(res.action).toBe('message'); }); test('URI with query and parameters', () => { const res = JID.parseURI('xmpp:user@example.com/resource?message;body=test;subject=weeeee'); expect(res.jid).toBe('user@example.com/resource'); expect(res.action).toBe('message'); expect(res.parameters).toEqual({ body: 'test', subject: 'weeeee' }); }); test('URI with encoded parameter values', () => { const res = JID.parseURI( 'xmpp:user@example.com/resource?message;body=test%20using%20%3d%20and%20%3b;subject=weeeee' ); expect(res.jid).toBe('user@example.com/resource'); expect(res.action).toBe('message'); expect(res.parameters).toEqual({ body: 'test using = and ;', subject: 'weeeee' }); }); test('Account selection only', () => { const res = JID.parseURI('xmpp://me@example.com'); expect(res.identity).toBe('me@example.com'); }); test('Account selection with JID', () => { const res = JID.parseURI('xmpp://me@example.com/user@example.com'); expect(res.identity).toBe('me@example.com'); expect(res.jid).toBe('user@example.com'); }); test('Account selection with JID with resource', () => { const res = JID.parseURI('xmpp://me@example.com/user@example.com/resource'); expect(res.identity).toBe('me@example.com'); expect(res.jid).toBe('user@example.com/resource'); }); test('Account selection with full JID and query action with parameters', () => { const res = JID.parseURI( 'xmpp://me@example.com/user@example.com/resource?message;body=kitchen%20sink;subject=allthethings' ); expect(res.identity).toBe('me@example.com'); expect(res.jid).toBe('user@example.com/resource'); expect(res.action).toBe('message'); expect(res.parameters).toEqual({ body: 'kitchen sink', subject: 'allthethings' }); }); test('Create URI with just account', () => { const res = JID.toURI({ identity: 'me@example.com' }); expect(res).toBe('xmpp://me@example.com'); }); test('Create URI with just JID', () => { const res = JID.toURI({ jid: 'user@example.com' }); expect(res).toBe('xmpp:user@example.com'); }); test('Create URI with just JID and resource', () => { const res = JID.toURI({ jid: 'user@example.com/@resource=' }); expect(res).toBe('xmpp:user@example.com/%40resource%3D'); }); test('Create URI with just JID and query action', () => { const res = JID.toURI({ action: 'subscribe', jid: 'user@example.com/@resource=' }); expect(res).toBe('xmpp:user@example.com/%40resource%3D?subscribe'); }); test('Create URI with JID and query action with parameters', () => { const res = JID.toURI({ action: 'message', jid: 'user@example.com/@?resource=', parameters: { body: 'testing', thread: 'thread-id' } }); expect(res).toBe( 'xmpp:user@example.com/%40%3Fresource%3D?message;body=testing;thread=thread-id' ); }); test('Create URI with selected account and query with parameters', () => { const res = JID.toURI({ action: 'message', identity: 'me@example.com', jid: 'user@example.com/@?resource=', parameters: { body: 'testing', thread: 'thread-id' } }); expect(res).toBe( 'xmpp://me@example.com/user@example.com/%40%3Fresource%3D?message;body=testing;thread=thread-id' ); }); test('Nasty examples from RFC', () => { const res = JID.toURI({ action: 'message', jid: 'nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com/repulsive !#"$%&\'()*+,-./:;<=>?@[\\]^_`{|}~resource' }); expect(res).toBe( "xmpp:nasty!%23%24%25()*%2B%2C-.%3B%3D%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com/repulsive%20!%23%22%24%25%26'()*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~resource?message" ); const res2 = JID.parseURI(res); expect(res2.jid).toBe( 'nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com/repulsive !#"$%&\'()*+,-./:;<=>?@[\\]^_`{|}~resource' ); }); test('Allowed responders', () => { const responders = JID.allowedResponders( 'user@domain/resource', 'remote-user@remote-domain/other-resource' ); expect(responders).toContain('remote-user@remote-domain/other-resource'); expect(responders).toContain('remote-user@remote-domain'); expect(responders).toContain('remote-domain'); expect(responders).toContain('user@domain/resource'); expect(responders).toContain('user@domain'); expect(responders).toContain('domain'); expect(responders).toContain(''); expect(responders).toContain(undefined); expect(responders.size).toBe(8); }); test('Get localpart', () => { expect(JID.getLocal('user@domain')).toBe('user'); }); test('Get domain', () => { expect(JID.getDomain('user@domain')).toBe('domain'); }); test('Get resource', () => { expect(JID.getResource('user@domain/resource')).toBe('resource'); }); test('Compare undefined', () => { expect(JID.equal('user@domain', undefined)).toBe(false); }); test('Compare bare undefined', () => { expect(JID.equalBare('user@domain', undefined)).toBe(false); }); test('To bare', () => { expect(JID.toBare('user@domain/resource')).toBe('user@domain'); }); test('To domain URI', () => { expect( JID.toURI({ jid: 'domain' }) ).toBe('xmpp:domain'); }); test('Multi-value parameter URI', () => { expect( JID.toURI({ jid: 'domain', action: 'foo', parameters: { bar: ['1', '2', '3'] } }) ).toBe('xmpp:domain?foo;bar=1;bar=2;bar=3'); }); test('Parse multi-value parameter URI', () => { expect(JID.parseURI('xmpp:domain?foo;bar=1;bar=2;bar=3')).toMatchObject({ action: 'foo', jid: 'domain', parameters: { bar: ['1', '2', '3'] } }); });
the_stack
import { mount } from 'enzyme'; import React from 'react'; import { Filters, Provider, SchemaSieve, Search, Select, Txt } from '../../'; import FiltersSummary from '../../components/Filters/Summary'; import { ViewListItem } from '../../components/Filters/ViewsMenu'; import { JSONSchema7 } from 'json-schema'; /* FieldSummary buttons in order: 0. Clear all filters 1. Save view 2. Edit single filter 3. Remove filter */ const schema = { type: 'object', properties: { Name: { title: 'Pokemon Name', type: 'string', }, Tag: { type: 'object', properties: { tag_name: { title: 'Name', description: 'key', type: 'string', }, tag_value: { description: 'value', title: 'Value', type: 'string', }, }, }, }, } as JSONSchema7; const filter = SchemaSieve.createFilter(schema, [ { field: 'Name', operator: 'is', value: 'Squirtle', }, ]); const tagIsFilter = SchemaSieve.createFilter(schema, [ { field: 'Tag', operator: 'is', value: { tag_name: 'rarity', tag_value: '10' }, }, ]); const tagIsNotFilter = SchemaSieve.createFilter(schema, [ { field: 'Tag', operator: 'is_not', value: { tag_name: 'rarity', tag_value: '10' }, }, ]); const view = { id: 'abcde', name: 'Test', scope: null, filters: [filter], }; const viewScopes = [ { slug: 'foo', name: 'foo', }, { slug: 'bar', name: 'bar', }, ]; describe('Filters component', () => { describe('filters property', () => { it('should not render a summary if there are no filters', () => { const component = mount( <Provider> <Filters schema={schema} /> </Provider>, ); expect(component.find(FiltersSummary)).toHaveLength(0); component.unmount(); }); it('should render a summary of filters that are provided as props', () => { const component = mount( <Provider> <Filters schema={schema} filters={[filter]} /> </Provider>, ); expect(component.find(FiltersSummary)).toHaveLength(1); component.unmount(); }); it('should render a summary of filters that are added as props after the component mounts', () => { const component = mount( React.createElement( (props) => ( <Provider> <Filters {...props} /> </Provider> ), { schema }, ), ); component.setProps({ filters: [filter] } as any); component.update(); expect(component.find(FiltersSummary)).toHaveLength(1); component.unmount(); }); it('should not render a summary of filters if they are removed after the component mounts', () => { const component = mount( React.createElement( (props) => ( <Provider> <Filters {...props} /> </Provider> ), { schema, filters: [filter] }, ), ); component.setProps({ filters: null } as any); component.update(); expect(component.find(FiltersSummary)).toHaveLength(0); component.unmount(); }); it('should show the correct label when filtering using "is" operator for both key and value properties of an object', () => { const component = mount( <Provider> <Filters schema={schema} filters={[tagIsFilter]} /> </Provider>, ); expect(component.find('button').at(4).text()).toBe('Tag is rarity : 10'); }); it('should show the correct label when filtering using "is_not" operator for both key and value properties of an object', () => { const component = mount( <Provider> <Filters schema={schema} filters={[tagIsNotFilter]} /> </Provider>, ); expect(component.find('button').at(4).text()).toBe( 'Tag is not rarity : 10', ); }); it('should remove buttons labels if compact property is set to true', () => { const component = mount( <Provider> <Filters compact={[true, true, true, true]} schema={schema} /> </Provider>, ); expect(component.find('button').at(0).text()).toBe(''); expect(component.find('button').at(1).text()).toBe(''); }); }); describe('save views modal', () => { it('should not show scopes selector if one or less scopes are passed', () => { const withOneViewScope = mount( <Provider> <Filters schema={schema} filters={[filter]} viewScopes={[viewScopes[0]]} /> </Provider>, ); const withNoViewScopes = mount( <Provider> <Filters schema={schema} filters={[filter]} viewScopes={[viewScopes[0]]} /> </Provider>, ); // Looking for 'Save view' button withOneViewScope.find('button').at(3).simulate('click'); expect(withOneViewScope.find(Select)).toHaveLength(0); withNoViewScopes.find('button').at(3).simulate('click'); expect(withNoViewScopes.find(Select)).toHaveLength(0); withOneViewScope.unmount(); withNoViewScopes.unmount(); }); it('should show scopes selector if viewScopes are passed', () => { const component = mount( <Provider> <Filters schema={schema} filters={[filter]} viewScopes={viewScopes} /> </Provider>, ); // Looking for 'Save view' button component.find('button').at(3).simulate('click'); expect(component.find(Select)).toHaveLength(1); component.unmount(); }); }); describe('views property', () => { it('should not render a views menu if there are no views', () => { const component = mount( <Provider> <Filters schema={schema} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find(ViewListItem)).toHaveLength(0); component.unmount(); }); it('should render a list of views that are provided as props', () => { const component = mount( <Provider> <Filters schema={schema} views={[view]} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find(ViewListItem)).toHaveLength(1); component.unmount(); }); it('should not render scoped views in the views menu if no scopes are passed', () => { const component = mount( <Provider> <Filters schema={schema} views={[{ ...view, scope: 'foo' }]} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find("[children='foo']")).toHaveLength(0); expect(component.find("[children='null']")).toHaveLength(0); component.unmount(); }); it('should not render scoped views in the views menu if one or less scopes are passed', () => { const component = mount( <Provider> <Filters schema={schema} views={[{ ...view, scope: 'foo' }]} viewScopes={[viewScopes[0]]} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find("[children='foo']")).toHaveLength(0); component.unmount(); }); it('should render scoped views in the views menu if more than one viewScopes are passed', () => { const component = mount( <Provider> <Filters schema={schema} views={[{ ...view, scope: 'foo' }]} viewScopes={viewScopes} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find(Txt).at(0).text()).toEqual('foo'); expect(component.find("[children='bar']")).toHaveLength(0); component.unmount(); }); it('should render views as "Unscoped" if they do not have a scope and more than one viewScopes are passed', () => { const component = mount( <Provider> <Filters schema={schema} views={[{ ...view }]} viewScopes={viewScopes} /> </Provider>, ); component.find('button').at(1).simulate('click'); expect(component.find(Txt).at(0).text()).toEqual('Unscoped'); expect(component.find("[children='foo']")).toHaveLength(0); expect(component.find("[children='bar']")).toHaveLength(0); component.unmount(); }); it('should render a list of views that are added as props after the component mounts', () => { const component = mount( React.createElement( (props) => ( <Provider> <Filters {...props} /> </Provider> ), { schema }, ), ); component.setProps({ views: [view] } as any); component.update(); component.find('button').at(1).simulate('click'); expect(component.find(ViewListItem)).toHaveLength(1); component.unmount(); }); it('should not render a list of views if they are removed after the component mounts', () => { const component = mount( React.createElement( (props) => ( <Provider> <Filters {...props} /> </Provider> ), { schema, views: [view] }, ), ); component.setProps({ views: null } as any); component.update(); component.find('button').at(1).simulate('click'); expect(component.find(ViewListItem)).toHaveLength(0); component.unmount(); }); it('should render when the schema contains an unknown type', () => { const unknownSchema = { type: 'object', properties: { test: { type: 'Foo Bar', }, }, } as any; const component = mount( <Provider> <Filters schema={unknownSchema} /> </Provider>, ); component.unmount(); }); it('should clear the `searchString` state prop after search filter removal', () => { const component = mount( <Provider> <Filters schema={schema} views={[view]} /> </Provider>, ); expect(component.find(Search)).toHaveLength(1); expect(component.find(Search).prop('value')).toEqual(''); component .find('input') .simulate('change', { target: { value: 'Squirtle' } }); const searchValue = component .find(FiltersSummary) .find('button') .at(2) .text(); expect(searchValue).toContain('Squirtle'); component.find(FiltersSummary).find('button').at(3).simulate('click'); expect(component.find(FiltersSummary)).toHaveLength(0); component.unmount(); }); it('should clear all filters and `searchString` when `clear all filters` gets clicked', () => { const defaultFilters = SchemaSieve.createFilter(schema, [ { field: 'Name', operator: 'contains', value: 's' }, { field: 'Name', operator: 'contains', value: 'q' }, ]); const component = mount( <Provider> <Filters schema={schema} filters={[defaultFilters]} /> </Provider>, ); expect(component.find(FiltersSummary)).toHaveLength(1); component .find('input') .simulate('change', { target: { value: 'Squirtle' } }); const searchValue = component .find(FiltersSummary) .find('button') .at(4) .text(); expect(searchValue).toContain('Squirtle'); component.find(FiltersSummary).find('button').at(0).simulate('click'); expect(component.find(FiltersSummary)).toHaveLength(0); const inputValue = component.find('input').prop('value'); expect(inputValue).toEqual(''); component.unmount(); }); }); });
the_stack
import React from 'react'; import { useLocation, Switch, Redirect, Route, Link, RouteComponentProps, } from 'react-router-dom'; import {Box, Flex} from 'theme-ui'; import {MenuItemProps} from 'antd/lib/menu/MenuItem'; import {colors, Badge, Layout, Menu, Sider} from '../common'; import {PlusOutlined, SettingOutlined} from '../icons'; import {INBOXES_DASHBOARD_SIDER_WIDTH} from '../../utils'; import * as API from '../../api'; import {Inbox} from '../../types'; import {useAuth} from '../auth/AuthProvider'; import {useConversations} from '../conversations/ConversationsProvider'; import ConversationsDashboard from '../conversations/ConversationsDashboard'; import ChatWidgetSettings from '../settings/ChatWidgetSettings'; import SlackReplyIntegrationDetails from '../integrations/SlackReplyIntegrationDetails'; import SlackSyncIntegrationDetails from '../integrations/SlackSyncIntegrationDetails'; import SlackIntegrationDetails from '../integrations/SlackIntegrationDetails'; import GmailIntegrationDetails from '../integrations/GmailIntegrationDetails'; import GoogleIntegrationDetails from '../integrations/GoogleIntegrationDetails'; import MattermostIntegrationDetails from '../integrations/MattermostIntegrationDetails'; import TwilioIntegrationDetails from '../integrations/TwilioIntegrationDetails'; import InboxEmailForwardingPage from './InboxEmailForwardingPage'; import InboxDetailsPage from './InboxDetailsPage'; import InboxesOverview from './InboxesOverview'; import InboxConversations from './InboxConversations'; import NewInboxModal from './NewInboxModal'; const getSectionKey = (pathname: string) => { const isInboxSettings = pathname === '/inboxes' || (pathname.startsWith('/inboxes') && pathname.indexOf('conversations') === -1); if (isInboxSettings) { return ['inbox-settings']; } else { return pathname.split('/').slice(1); // Slice off initial slash } }; export const NewInboxModalMenuItem = ({ onSuccess, ...props }: { onSuccess: (inbox: Inbox) => void; } & MenuItemProps) => { const [isModalOpen, setModalOpen] = React.useState(false); const handleOpenModal = () => setModalOpen(true); const handleCloseModal = () => setModalOpen(false); const handleSuccess = (inbox: Inbox) => { handleCloseModal(); onSuccess(inbox); }; return ( <> <Menu.Item {...props} onClick={handleOpenModal} /> <NewInboxModal visible={isModalOpen} onCancel={handleCloseModal} onSuccess={handleSuccess} /> </> ); }; const InboxesDashboard = (props: RouteComponentProps) => { const {pathname} = useLocation(); const {currentUser} = useAuth(); const {unread} = useConversations(); const [inboxes, setCustomInboxes] = React.useState<Array<Inbox>>([]); const [section, key] = getSectionKey(pathname); const totalNumUnread = unread.conversations.open || 0; const isAdminUser = currentUser?.role === 'admin'; React.useEffect(() => { API.fetchInboxes().then((inboxes) => setCustomInboxes(inboxes)); }, []); const handleInboxCreated = async (inbox: Inbox) => { setCustomInboxes([...inboxes, inbox]); props.history.push(`/inboxes/${inbox.id}`); }; return ( <Layout style={{background: colors.white}}> <Sider className="Dashboard-Sider" width={INBOXES_DASHBOARD_SIDER_WIDTH} style={{ overflow: 'auto', height: '100vh', position: 'fixed', color: colors.white, }} > <Flex sx={{flexDirection: 'column', height: '100%'}}> <Box py={3} sx={{flex: 1}}> {/* TODO: eventually we should design our own sidebar menu so we have more control over the UX */} <Menu selectedKeys={[section, key]} defaultOpenKeys={['conversations', 'channels', 'inboxes']} mode="inline" theme="dark" > <Menu.SubMenu key="conversations" title="Conversations"> <Menu.Item key="all"> <Link to="/conversations/all"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>All</Box> <Badge count={totalNumUnread} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="me"> <Link to="/conversations/me"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>Assigned to me</Box> <Badge count={unread.conversations.assigned || 0} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="mentions"> <Link to="/conversations/mentions"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>Mentions</Box> <Badge count={unread.conversations.mentioned || 0} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="unread"> <Link to="/conversations/unread"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>Unread</Box> <Badge count={unread.conversations.unread || 0} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="unassigned"> <Link to="/conversations/unassigned"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>Unassigned</Box> <Badge count={unread.conversations.unassigned} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="priority"> <Link to="/conversations/priority"> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>Prioritized</Box> <Badge count={unread.conversations.priority} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> <Menu.Item key="closed"> <Link to="/conversations/closed">Closed</Link> </Menu.Item> </Menu.SubMenu> <Menu.SubMenu key="inboxes" title="Inboxes"> {inboxes.map((inbox) => { const {id, name} = inbox; return ( <Menu.Item key={id}> <Link to={`/inboxes/${id}/conversations`}> <Flex sx={{ alignItems: 'center', justifyContent: 'space-between', }} > <Box mr={2}>{name}</Box> <Badge count={unread.inboxes[id] || 0} style={{borderColor: '#FF4D4F'}} /> </Flex> </Link> </Menu.Item> ); })} </Menu.SubMenu> {isAdminUser && ( <NewInboxModalMenuItem key="add-inbox" icon={<PlusOutlined />} title="Add inbox" onSuccess={handleInboxCreated} > Add inbox </NewInboxModalMenuItem> )} {isAdminUser && ( <Menu.Item key="inbox-settings" icon={<SettingOutlined />} title="Inbox settings" > <Link to="/inboxes">Configure inboxes</Link> </Menu.Item> )} </Menu> </Box> </Flex> </Sider> <Layout style={{ background: colors.white, marginLeft: INBOXES_DASHBOARD_SIDER_WIDTH, }} > <Switch> <Route path="/conversations/:bucket/:conversation_id" component={ConversationsDashboard} /> <Route path="/conversations/:bucket" component={ConversationsDashboard} /> <Route path="/inboxes/:inbox_id/conversations/:conversation_id" component={InboxConversations} /> <Route path="/inboxes/:inbox_id/conversations" component={InboxConversations} /> <Route path="/inboxes/:inbox_id/conversations" component={InboxesDashboard} /> <Route path="/inboxes/:inbox_id/chat-widget" component={ChatWidgetSettings} /> <Route path="/inboxes/:inbox_id/integrations/slack/reply" component={SlackReplyIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/slack/support" component={SlackSyncIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/slack" component={SlackIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/google/gmail" component={GmailIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/google" component={GoogleIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/mattermost" component={MattermostIntegrationDetails} /> <Route path="/inboxes/:inbox_id/integrations/twilio" component={TwilioIntegrationDetails} /> <Route path="/inboxes/:inbox_id/email-forwarding" component={InboxEmailForwardingPage} /> <Route path="/inboxes/:inbox_id" component={InboxDetailsPage} /> <Route path="/inboxes" component={InboxesOverview} /> <Route path="*" render={() => <Redirect to="/conversations/all" />} /> </Switch> </Layout> </Layout> ); }; export default InboxesDashboard;
the_stack
import { Filename, PortablePath } from '@yarnpkg/fslib'; import { Limit } from 'p-limit'; import { Writable } from 'stream'; import { MultiFetcher } from './MultiFetcher'; import { MultiResolver } from './MultiResolver'; import { Plugin, Hooks } from './Plugin'; import { Report } from './Report'; import { TelemetryManager } from './TelemetryManager'; import * as formatUtils from './formatUtils'; import * as miscUtils from './miscUtils'; import { IdentHash, Package, PackageExtension } from './types'; export declare const ENVIRONMENT_PREFIX = "yarn_"; export declare const DEFAULT_RC_FILENAME: Filename; export declare const DEFAULT_LOCK_FILENAME: Filename; export declare const SECRET = "********"; export declare enum SettingsType { ANY = "ANY", BOOLEAN = "BOOLEAN", ABSOLUTE_PATH = "ABSOLUTE_PATH", LOCATOR = "LOCATOR", LOCATOR_LOOSE = "LOCATOR_LOOSE", NUMBER = "NUMBER", STRING = "STRING", SECRET = "SECRET", SHAPE = "SHAPE", MAP = "MAP" } export declare type FormatType = formatUtils.Type; export declare const FormatType: typeof formatUtils.Type; export declare type BaseSettingsDefinition<T extends SettingsType = SettingsType> = { description: string; type: T; } & ({ isArray?: false; } | { isArray: true; concatenateValues?: boolean; }); export declare type ShapeSettingsDefinition = BaseSettingsDefinition<SettingsType.SHAPE> & { properties: { [propertyName: string]: SettingsDefinition; }; }; export declare type MapSettingsDefinition = BaseSettingsDefinition<SettingsType.MAP> & { valueDefinition: SettingsDefinitionNoDefault; normalizeKeys?: (key: string) => string; }; export declare type SimpleSettingsDefinition = BaseSettingsDefinition<Exclude<SettingsType, SettingsType.SHAPE | SettingsType.MAP>> & { default: any; defaultText?: any; isNullable?: boolean; values?: Array<any>; }; export declare type SettingsDefinitionNoDefault = MapSettingsDefinition | ShapeSettingsDefinition | Omit<SimpleSettingsDefinition, 'default'>; export declare type SettingsDefinition = MapSettingsDefinition | ShapeSettingsDefinition | SimpleSettingsDefinition; export declare type PluginConfiguration = { modules: Map<string, any>; plugins: Set<string>; }; export declare const coreDefinitions: { [coreSettingName: string]: SettingsDefinition; }; /** * @deprecated Use miscUtils.ToMapValue */ export declare type MapConfigurationValue<T extends object> = miscUtils.ToMapValue<T>; export interface ConfigurationValueMap { lastUpdateCheck: string | null; yarnPath: PortablePath; ignorePath: boolean; ignoreCwd: boolean; cacheKeyOverride: string | null; globalFolder: PortablePath; cacheFolder: PortablePath; compressionLevel: `mixed` | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; virtualFolder: PortablePath; bstatePath: PortablePath; lockfileFilename: Filename; installStatePath: PortablePath; immutablePatterns: Array<string>; rcFilename: Filename; enableGlobalCache: boolean; enableAbsoluteVirtuals: boolean; enableColors: boolean; enableHyperlinks: boolean; enableInlineBuilds: boolean; enableProgressBars: boolean; enableTimers: boolean; preferAggregateCacheInfo: boolean; preferInteractive: boolean; preferTruncatedLines: boolean; progressBarStyle: string | undefined; defaultLanguageName: string; defaultProtocol: string; enableTransparentWorkspaces: boolean; enableMirror: boolean; enableNetwork: boolean; httpProxy: string | null; httpsProxy: string | null; unsafeHttpWhitelist: Array<string>; httpTimeout: number; httpRetry: number; networkConcurrency: number; networkSettings: Map<string, miscUtils.ToMapValue<{ caFilePath: PortablePath | null; enableNetwork: boolean | null; httpProxy: string | null; httpsProxy: string | null; }>>; caFilePath: PortablePath | null; enableStrictSsl: boolean; logFilters: Array<miscUtils.ToMapValue<{ code?: string; text?: string; level?: formatUtils.LogLevel | null; }>>; enableTelemetry: boolean; telemetryInterval: number; telemetryUserId: string | null; enableScripts: boolean; enableImmutableCache: boolean; checksumBehavior: string; packageExtensions: Map<string, miscUtils.ToMapValue<{ dependencies?: Map<string, string>; peerDependencies?: Map<string, string>; peerDependenciesMeta?: Map<string, miscUtils.ToMapValue<{ optional?: boolean; }>>; }>>; } export declare type PackageExtensionData = miscUtils.MapValueToObjectValue<miscUtils.MapValue<ConfigurationValueMap['packageExtensions']>>; declare type SimpleDefinitionForType<T> = SimpleSettingsDefinition & { type: (T extends boolean ? SettingsType.BOOLEAN : never) | (T extends number ? SettingsType.NUMBER : never) | (T extends PortablePath ? SettingsType.ABSOLUTE_PATH : never) | (T extends string ? SettingsType.LOCATOR | SettingsType.LOCATOR_LOOSE | SettingsType.SECRET | SettingsType.STRING : never) | SettingsType.ANY; }; declare type DefinitionForTypeHelper<T> = T extends Map<string, infer U> ? (MapSettingsDefinition & { valueDefinition: Omit<DefinitionForType<U>, 'default'>; }) : T extends miscUtils.ToMapValue<infer U> ? (ShapeSettingsDefinition & { properties: ConfigurationDefinitionMap<U>; }) : SimpleDefinitionForType<T>; declare type DefinitionForType<T> = T extends Array<infer U> ? (DefinitionForTypeHelper<U> & { isArray: true; }) : (DefinitionForTypeHelper<T> & { isArray?: false; }); export declare type ConfigurationDefinitionMap<V = ConfigurationValueMap> = { [K in keyof V]: DefinitionForType<V[K]>; }; declare type SettingTransforms = { hideSecrets: boolean; getNativePaths: boolean; }; export declare enum ProjectLookup { LOCKFILE = 0, MANIFEST = 1, NONE = 2 } export declare type FindProjectOptions = { lookup?: ProjectLookup; strict?: boolean; usePath?: boolean; useRc?: boolean; }; export declare class Configuration { static telemetry: TelemetryManager | null; startingCwd: PortablePath; projectCwd: PortablePath | null; plugins: Map<string, Plugin>; settings: Map<string, SettingsDefinition>; values: Map<string, any>; sources: Map<string, string>; invalid: Map<string, string>; packageExtensions: Map<IdentHash, Array<[string, Array<PackageExtension>]>>; limits: Map<string, Limit>; /** * Instantiate a new configuration object with the default values from the * core. You typically don't want to use this, as it will ignore the values * configured in the rc files. Instead, prefer to use `Configuration#find`. */ static create(startingCwd: PortablePath, plugins?: Map<string, Plugin>): Configuration; static create(startingCwd: PortablePath, projectCwd: PortablePath | null, plugins?: Map<string, Plugin>): Configuration; /** * Instantiate a new configuration object exposing the configuration obtained * from reading the various rc files and the environment settings. * * The `pluginConfiguration` parameter is expected to indicate: * * 1. which modules should be made available to plugins when they require a * package (this is the dynamic linking part - for example we want all the * plugins to use the exact same version of @yarnpkg/core, which also is the * version used by the running Yarn instance). * * 2. which of those modules are actually plugins that need to be injected * within the configuration. * * Note that some extra plugins will be automatically added based on the * content of the rc files - with the rc plugins taking precedence over * the other ones. * * One particularity: the plugin initialization order is quite strict, with * plugins listed in /foo/bar/.yarnrc.yml taking precedence over plugins * listed in /foo/.yarnrc.yml and /.yarnrc.yml. Additionally, while plugins * can depend on one another, they can only depend on plugins that have been * instantiated before them (so a plugin listed in /foo/.yarnrc.yml can * depend on another one listed on /foo/bar/.yarnrc.yml, but not the other * way around). */ static find(startingCwd: PortablePath, pluginConfiguration: PluginConfiguration | null, { lookup, strict, usePath, useRc }?: FindProjectOptions): Promise<Configuration>; static findRcFiles(startingCwd: PortablePath): Promise<{ path: PortablePath; cwd: PortablePath; data: any; }[]>; static findHomeRcFile(): Promise<{ path: PortablePath; cwd: PortablePath; data: any; } | null>; static findProjectCwd(startingCwd: PortablePath, lockfileFilename: Filename | null): Promise<PortablePath | null>; static updateConfiguration(cwd: PortablePath, patch: { [key: string]: ((current: unknown) => unknown) | {} | undefined; } | ((current: { [key: string]: unknown; }) => { [key: string]: unknown; })): Promise<void>; static updateHomeConfiguration(patch: { [key: string]: ((current: unknown) => unknown) | {} | undefined; } | ((current: { [key: string]: unknown; }) => { [key: string]: unknown; })): Promise<void>; private constructor(); activatePlugin(name: string, plugin: Plugin): void; private importSettings; useWithSource(source: string, data: { [key: string]: unknown; }, folder: PortablePath, opts?: { strict?: boolean; overwrite?: boolean; }): void; use(source: string, data: { [key: string]: unknown; }, folder: PortablePath, { strict, overwrite }?: { strict?: boolean; overwrite?: boolean; }): void; get<K extends keyof ConfigurationValueMap>(key: K): ConfigurationValueMap[K]; /** @deprecated pass in a known configuration key instead */ get<T>(key: string): T; /** @note Type will change to unknown in a future major version */ get(key: string): any; getSpecial<T = any>(key: string, { hideSecrets, getNativePaths }: Partial<SettingTransforms>): T; getSubprocessStreams(logFile: PortablePath, { header, prefix, report }: { header?: string; prefix: string; report: Report; }): { stdout: Writable; stderr: Writable; }; makeResolver(): MultiResolver; makeFetcher(): MultiFetcher; getLinkers(): import("./Linker").Linker[]; refreshPackageExtensions(): Promise<void>; normalizePackage(original: Package): Package; getLimit(key: string): Limit; triggerHook<U extends Array<any>, V, HooksDefinition = Hooks>(get: (hooks: HooksDefinition) => ((...args: U) => V) | undefined, ...args: U): Promise<void>; triggerMultipleHooks<U extends Array<any>, V, HooksDefinition = Hooks>(get: (hooks: HooksDefinition) => ((...args: U) => V) | undefined, argsList: Array<U>): Promise<void>; reduceHook<U extends Array<any>, V, HooksDefinition = Hooks>(get: (hooks: HooksDefinition) => ((reduced: V, ...args: U) => Promise<V>) | undefined, initialValue: V, ...args: U): Promise<V>; firstHook<U extends Array<any>, V, HooksDefinition = Hooks>(get: (hooks: HooksDefinition) => ((...args: U) => Promise<V>) | undefined, ...args: U): Promise<Exclude<V, void> | null>; /** * @deprecated Prefer using formatUtils.pretty instead, which is type-safe */ format(value: string, formatType: formatUtils.Type | string): string; } export {};
the_stack
import { log } from "../util"; import { Token } from "../tokenizer/token"; import { TokenType } from "../tokenizer/token-type"; import { AstNode } from "./ast"; import { AstNodeType } from "./ast-node-type"; function addTokensToAst(tokens: Array<Token>, ast: Array<AstNode>): void { for (let i: i32 = 0; i < tokens.length; i++) { let indexOffset = addAstNode(ast, tokens, i); i += indexOffset; } } export function markdownTokenParser(tokens: Array<Token>): Array<AstNode> { let ast = new Array<AstNode>(0); addTokensToAst(tokens, ast); return ast; } function getNewAstNode(): AstNode { // AS Bugfix: Make sure the child array for the AstNode is properly initialized // E.g, Make sure the child nodes of the ast is properly allocated as a new AST let astNode: AstNode = new AstNode(); astNode.childNodes = new Array<AstNode>(0); return astNode; } function addAstNode( ast: Array<AstNode>, tokens: Array<Token>, tokenIndex: i32 ): i32 { let astNode: AstNode = getNewAstNode(); let token: Token = tokens[tokenIndex]; if (token.type == TokenType.NEWLINE) { astNode.type = AstNodeType.NEWLINE; astNode.value = token.value; ast.push(astNode); return 0; } if (token.type == TokenType.WHITESPACE) { astNode.type = AstNodeType.WHITESPACE; astNode.value = token.value; ast.push(astNode); return 0; } if (token.type == TokenType.HEADER) { // Initialize the offset for finding the header let indexOffset = 0; // Find the level of the header let headerLevel = 1; while ( tokenIndex + indexOffset + 1 < tokens.length - 1 && tokens[tokenIndex + indexOffset + 1].type === TokenType.HEADER ) { headerLevel += 1; indexOffset += 1; } // Check if the next value is whitespace if (tokens[tokenIndex + indexOffset + 1].type === TokenType.WHITESPACE) { // We have a header // Increase the offset once more indexOffset += 1; // Get the content of the header let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + indexOffset + 1, TokenType.NEWLINE ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.HEADER; astNode.value = headerLevel.toString(); indexOffset += offsetTokenLength; ast.push(astNode); // Go through the child tokens as well addTokensToAst(contentTokens, astNode.childNodes); return offsetTokenLength + headerLevel; } } if (token.type == TokenType.ITALICS) { if ( checkIfTypeIsFoundBeforeOtherType( tokens, tokenIndex + 1, TokenType.ITALICS, TokenType.NEWLINE ) ) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.ITALICS ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.ITALICS; // Go through the child tokens as well addTokensToAst(contentTokens, astNode.childNodes); ast.push(astNode); return offsetTokenLength + 1; } } if (token.type == TokenType.BOLD) { if ( checkIfTypeIsFoundBeforeOtherType( tokens, tokenIndex + 1, TokenType.BOLD, TokenType.NEWLINE ) ) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.BOLD ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.BOLD; // Go through the child tokens as well addTokensToAst(contentTokens, astNode.childNodes); ast.push(astNode); return offsetTokenLength + 1; } } if (token.type == TokenType.STRIKETHROUGH) { if ( checkIfTypeIsFoundBeforeOtherType( tokens, tokenIndex + 1, TokenType.STRIKETHROUGH, TokenType.NEWLINE ) ) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.STRIKETHROUGH ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.STRIKETHROUGH; // Go through the child tokens as well addTokensToAst(contentTokens, astNode.childNodes); ast.push(astNode); return offsetTokenLength + 1; } } // Doing lists as one, as they share list item logic if ( token.type == TokenType.UNORDERED_LIST_ITEM || token.type == TokenType.ORDERED_LIST_ITEM ) { // Set up the item type we are looking for let listItemType: string = ""; // Set our list node, and add it to the parent ast. if (token.type == TokenType.UNORDERED_LIST_ITEM) { astNode.type = AstNodeType.UNORDERED_LIST; listItemType = TokenType.UNORDERED_LIST_ITEM; } else { astNode.type = AstNodeType.ORDERED_LIST; listItemType = TokenType.ORDERED_LIST_ITEM; } ast.push(astNode); // Need to add all the list items to our list let tokensToSkip = 0; let tokensSkippedForWhitespace = 0; let listItemTokenIndex = tokenIndex; while ( listItemTokenIndex + tokensSkippedForWhitespace < tokens.length && tokens[listItemTokenIndex + tokensSkippedForWhitespace].type == listItemType ) { // Add the tokens we skipped for whitespace to our other skip/index values tokensToSkip += tokensSkippedForWhitespace; listItemTokenIndex += tokensSkippedForWhitespace; // Create the node for the list item let listItemAstNode: AstNode = getNewAstNode(); listItemAstNode.type = AstNodeType.LIST_ITEM; // Get its content tokens let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, listItemTokenIndex + 1, TokenType.NEWLINE ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; // Add the content to the list item addTokensToAst(contentTokens, listItemAstNode.childNodes); // Add the list item to the list astNode.childNodes.push(listItemAstNode); let nextTokenIndex = offsetTokenLength + 2; // Increase our values to keep looking through nodes! tokensToSkip += nextTokenIndex; listItemTokenIndex += nextTokenIndex; // Need to handle whitespace here for tabbing as well tokensSkippedForWhitespace = 0; while ( listItemTokenIndex + tokensSkippedForWhitespace < tokens.length && tokens[listItemTokenIndex + tokensSkippedForWhitespace].type == TokenType.WHITESPACE ) { tokensSkippedForWhitespace += 1; } } return tokensToSkip; } // Let's look for images if (token.type == TokenType.IMAGE_START) { let altTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.BRACKET_END ); let altText: string = getTokensAsString(altTokens); let altTextOffsetTokenLength: i32 = altTokens.length; let altTextAstNode = getNewAstNode(); altTextAstNode.type = "Alt"; altTextAstNode.value = altText; // We have the alt text, if this is an image // We need to check if this is immediately followed by a parentheses if ( tokens[tokenIndex + altTextOffsetTokenLength + 2].type == TokenType.PAREN_START ) { let imageTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + altTextOffsetTokenLength + 3, TokenType.PAREN_END ); let imageUrl: string = getTokensAsString(imageTokens); let imageUrlOffsetTokenLength: i32 = imageTokens.length; // Let's create the Ast Node for the image astNode.type = AstNodeType.IMAGE; astNode.value = imageUrl; astNode.childNodes.push(altTextAstNode); ast.push(astNode); return altTextOffsetTokenLength + imageUrlOffsetTokenLength + 4; } } // Let's look for links if (token.type == TokenType.BRACKET_START) { let linkTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.BRACKET_END ); let linkContent: string = getTokensAsString(linkTokens); let linkContentOffsetTokenLength: i32 = linkTokens.length; let linkContentAstNode = getNewAstNode(); linkContentAstNode.type = "Link Content"; linkContentAstNode.value = linkContent; // We have the link content, if this is an link // We need to check if this is immediately followed by a parentheses if ( tokens[tokenIndex + linkContentOffsetTokenLength + 2].type == TokenType.PAREN_START ) { let urlTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + linkContentOffsetTokenLength + 3, TokenType.PAREN_END ); let urlContent: string = getTokensAsString(urlTokens); let urlContentOffsetTokenLength: i32 = urlTokens.length; // Let's create the Ast Node for the image astNode.type = AstNodeType.LINK; astNode.value = urlContent; astNode.childNodes.push(linkContentAstNode); ast.push(astNode); return linkContentOffsetTokenLength + urlContentOffsetTokenLength + 4; } } if (token.type == TokenType.BLOCK_QUOTE) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.NEWLINE ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.BLOCK_QUOTE; astNode.value = content; ast.push(astNode); return offsetTokenLength + 1; } if (token.type == TokenType.CODE_BLOCK) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.CODE_BLOCK ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.CODE_BLOCK; astNode.value = content; ast.push(astNode); return offsetTokenLength + 1; } if (token.type == TokenType.INLINE_CODE) { if ( checkIfTypeIsFoundBeforeOtherType( tokens, tokenIndex + 1, TokenType.INLINE_CODE, TokenType.NEWLINE ) ) { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, tokenIndex + 1, TokenType.INLINE_CODE ); let content: string = getTokensAsString(contentTokens); let offsetTokenLength: i32 = contentTokens.length; astNode.type = AstNodeType.INLINE_CODE; astNode.value = content; ast.push(astNode); return offsetTokenLength + 1; } } if ( token.type == TokenType.HORIZONTAL_LINE && tokens[tokenIndex + 1].type == TokenType.NEWLINE ) { astNode.type = AstNodeType.HORIZONTAL_LINE; ast.push(astNode); return 0; } // It did not match our cases, let's assume the node is for characters astNode.type = AstNodeType.CHARACTER; astNode.value = token.value; ast.push(astNode); return 0; } // Returns an array of strings where: // 0: is the content between the start, and the found ending token. // 1: is the number of tokens found before reaching the end. function getOffsetOfTokensUntilTokenReached( tokens: Array<Token>, startTokenIndex: i32, stopTokenType: string ): Array<string> { let contentTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, startTokenIndex, stopTokenType ); let content: string = ""; for (let i = 0; i < contentTokens.length; i++) { content += contentTokens[i].value; } let response = new Array<string>(); response.push(content); response.push(contentTokens.length.toString()); return response; } // Function to return tokens as a string function getTokensAsString(tokens: Array<Token>): string { let content: string = ""; for (let i = 0; i < tokens.length; i++) { content += tokens[i].value; } return content; } function checkIfTypeIsFoundBeforeOtherType( tokens: Array<Token>, startTokenIndex: i32, checkTokenType: string, otherTokenType: string ): boolean { let checkTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, startTokenIndex, checkTokenType ); let otherTokens: Array<Token> = getAllTokensUntilTokenReached( tokens, startTokenIndex, otherTokenType ); if (checkTokens.length < otherTokens.length) { return true; } else { return false; } } function getAllTokensUntilTokenReached( tokens: Array<Token>, startTokenIndex: i32, stopTokenType: string ): Array<Token> { let responseTokens = new Array<Token>(); for (let i = startTokenIndex; i < tokens.length; i++) { let token = tokens[i]; if (token.type == stopTokenType) { i = tokens.length; } else { responseTokens.push(token); } } return responseTokens; }
the_stack
import * as treeDescription from "./tree-description"; import {TreeNode, TreeDescription, Crosslink} from "./tree-description"; import {assert, Json, forceToString, tryToString, formatMetric, hasOwnProperty, hasSubOject} from "./loader-utils"; // Convert Postgres JSON to a D3 tree function convertPostgres(node: Json, parentKey: string): TreeNode | TreeNode[] { if (tryToString(node) !== undefined) { return { text: tryToString(node), }; } else if (typeof node === "object" && !Array.isArray(node) && node !== null) { // "Object" nodes let explicitChildren = [] as TreeNode[]; const additionalChildren = [] as TreeNode[]; const properties = new Map<string, string>(); // Take the first present tagKey as the new tag. Add all others as properties const tagKeys = ["Node Type"]; let tag: string | undefined; for (const tagKey of tagKeys) { if (!node.hasOwnProperty(tagKey)) { continue; } if (tag === undefined) { tag = tryToString(node[tagKey]); } else { properties.set(tagKey, forceToString(node[tagKey])); } } if (tag === undefined) { tag = parentKey; } // Add the following keys as children const childKeys = ["Plan", "Plans"]; for (const key of childKeys) { if (!node.hasOwnProperty(key)) { continue; } const child = convertPostgres(node[key], key); if (Array.isArray(child)) { explicitChildren = explicitChildren.concat(child); } else { explicitChildren.push(child); } } // Add the following keys as children only when they refer to objects and display as properties if not const objectKeys = [""]; for (const key of objectKeys) { if (!node.hasOwnProperty(key)) { continue; } if (typeof node[key] !== "object") { properties.set(key, forceToString(node[key])); continue; } const child = convertPostgres(node[key], key); if (Array.isArray(child)) { explicitChildren = explicitChildren.concat(child); } else { explicitChildren.push(child); } } // Display these properties always as properties, even if they are more complex const propertyKeys = [""]; for (const key of propertyKeys) { if (node.hasOwnProperty(key)) { properties.set(key, forceToString(node[key])); } } // Display all other properties adaptively: simple expressions are displayed as properties, all others as part of the tree const handledKeys = tagKeys.concat(childKeys, objectKeys, propertyKeys); for (const key of Object.getOwnPropertyNames(node)) { if (handledKeys.indexOf(key) !== -1) { continue; } // Try to display as string property const str = tryToString(node[key]); if (str !== undefined) { properties.set(key, str); continue; } // Display as part of the tree const innerNodes = convertPostgres(node[key], key); if (Array.isArray(innerNodes)) { additionalChildren.push({tag: key, children: innerNodes}); } else { additionalChildren.push({tag: key, children: [innerNodes]}); } } // Display the cardinality on the links between the nodes let edgeLabel: string | undefined = undefined; let edgeLabelClass: string | undefined = undefined; if (node.hasOwnProperty("Plan Rows") && typeof node["Plan Rows"] === "number") { edgeLabel = formatMetric(node["Plan Rows"]); if (node.hasOwnProperty("Actual Rows") && typeof node["Actual Rows"] === "number") { edgeLabel += "," + formatMetric(node["Actual Rows"]); // Highlight significant differences between planned and actual rows const num0 = Number(node["Plan Rows"]); const num1 = Number(node["Actual Rows"]); if (num0 > num1 * 10 || num0 * 10 < num1) { edgeLabelClass = "qg-link-label-highlighted"; } } } // Collapse nodes as appropriate let children: TreeNode[]; let _children: TreeNode[]; if (node.hasOwnProperty("Triggers") || node.hasOwnProperty("Node Type")) { // For operators, the additionalChildren are collapsed by default children = explicitChildren; _children = explicitChildren.concat(additionalChildren); } else { // Everything else (usually expressions): display uncollapsed children = explicitChildren.concat(additionalChildren); _children = []; } // Sort properties by key const sortedProperties = new Map<string, string>(); for (const k of Array.from(properties.keys()).sort()) { sortedProperties.set(k, properties.get(k) as string); } // Build the converted node return { tag: tag, properties: sortedProperties, children: children, _children: _children, edgeLabel: edgeLabel, edgeLabelClass: edgeLabelClass, }; } else if (Array.isArray(node)) { // "Array" nodes const listOfObjects = [] as TreeNode[]; for (let index = 0; index < node.length; ++index) { const value = node[index]; const innerNode = convertPostgres(value, parentKey + "." + index.toString()); // objectify nested arrays if (Array.isArray(innerNode)) { innerNode.forEach(function(value, _index) { listOfObjects.push(value); }); } else { listOfObjects.push(innerNode); } } return listOfObjects; } throw new Error("Invalid Postgres query plan"); } // Function to generate nodes' display names based on their properties function generateDisplayNames(treeRoot: TreeNode) { treeDescription.visitTreeNodes( treeRoot, function(node) { switch (node.tag) { case "Hash Join": case "Nested Loop": case "Merge Join": if (node.hasOwnProperty("properties")) { switch (node.properties?.get("Join Type")) { case "Inner": node.name = node.tag; node.symbol = "inner-join-symbol"; break; case "Full Outer": node.name = node.tag; node.symbol = "full-join-symbol"; break; case "Left Outer": node.name = node.tag; node.symbol = "left-join-symbol"; break; case "Right Outer": node.name = node.tag; node.symbol = "right-join-symbol"; break; default: node.name = node.tag; node.symbol = "inner-join-symbol"; break; } } break; case "Bitmap Heap Scan": case "Bitmap Index Scan": case "Custom Scan": case "Foreign Scan": case "Function Scan": case "Index Only Scan": case "Index Scan": case "Named Tuplestore Scan": case "Sample Scan": case "Subquery Scan": case "Table Function Scan": case "Tid Scan": case "Values Scan": node.name = node.tag; node.symbol = "table-symbol"; break; case "Seq Scan": node.name = node.properties?.get("Relation Name") ?? node.tag; node.symbol = "table-symbol"; break; case "CTE Scan": case "Materialize": case "WorkTable Scan": node.name = node.tag; node.symbol = "temp-table-symbol"; break; case "Incremental Sort": case "Sort": node.name = node.tag; node.symbol = "sort-symbol"; break; case "Result": node.name = node.tag; node.symbol = "const-table-symbol"; break; case "Limit": node.name = node.tag; node.symbol = "filter-symbol"; break; default: if (node.tag) { node.name = node.tag; } else if (node.text) { node.name = node.text; } else { node.name = ""; } break; } }, treeDescription.allChildren, ); } // Color graph per Foreign Scan relations function colorForeignScan(node: TreeNode, foreignScan?: string) { if (node.tag === "Foreign Scan") { // A Foreign Scan of one relation has a Schema or a Relations if multiple const schema = node.properties?.get("Schema"); const relations = node.properties?.get("Relations"); if (schema) { foreignScan = schema; } else if (relations) { foreignScan = relations.split(/[(.]/).find(token => token !== ""); } } if (foreignScan !== undefined) { node.nodeClass = "qg-" + foreignScan; } for (const child of treeDescription.allChildren(node)) { colorForeignScan(child, foreignScan); } } // Color graph per a node's relative execution time // Actual Total Time is cumulative // Nodes with Actual Loops > 1 record an average Actual Total Time // Parallelized nodes have Actual Loops = Workers Launched + 1 for the leader // Not all Postgres plans have a root Execution Time even when children have Actual Total Time function colorRelativeExecutionTime(root: TreeNode) { let executionTime = root.properties?.get("Execution Time"); if (executionTime === undefined) { for (const child of treeDescription.allChildren(root)) { const actualTotalTime = child.properties?.get("Actual Total Time"); if (actualTotalTime) { assert(executionTime === undefined, "Unexpected result child node"); executionTime = actualTotalTime; } } } if (executionTime) { for (const child of treeDescription.allChildren(root)) { colorChildRelativeExecutionRatio(child, Number(executionTime), 1); } } } function colorChildRelativeExecutionRatio(node: TreeNode, executionTime: number, degreeOfParallelism: number) { let childrenTime = 0; if (node.tag === "Gather" || node.tag === "Gather Merge") { const workersLaunched = node.properties?.get("Workers Launched"); assert(workersLaunched !== undefined, "Unexpected Workers Launched"); degreeOfParallelism = Number(workersLaunched) + 1 /* leader */; } for (const child of treeDescription.allChildren(node)) { const actualTotalTime = child.properties?.get("Actual Total Time"); if (actualTotalTime) { const actualLoops = child.properties?.get("Actual Loops"); assert(actualLoops !== undefined, "Unexpected Actual Loops"); const childLoops = Number(actualLoops) / degreeOfParallelism; childrenTime += Number(actualTotalTime) * childLoops; } } const actualTotalTime = node.properties?.get("Actual Total Time"); if (actualTotalTime) { const nodeTotalTime = Number(actualTotalTime); const actualLoops = node.properties?.get("Actual Loops"); assert(actualLoops !== undefined, "Unexpected Actual Loops"); let nodeLoops = Number(actualLoops); if (node.tag !== "Gather" && node.tag !== "Gather Merge") { nodeLoops /= degreeOfParallelism; } const relativeTotalTime = nodeTotalTime * nodeLoops - childrenTime; const relativeExecutionRatio = relativeTotalTime / executionTime; // TODO: remove Actual Total Time of a CTE from referencing CTE Scan subplans // TODO: assert(relativeExecutionRatio >= 0, "Unexpected relative execution ratio"); assert(node.properties !== undefined); node.properties.set("~Relative Time", relativeTotalTime.toFixed(3)); node.properties.set("~Relative Time Ratio", relativeExecutionRatio.toFixed(3)); const l = (95 + (72 - 95) * relativeExecutionRatio).toFixed(3); const hsl = "hsl(309, 84%, " + l + "%)"; node.rectFill = hsl; node.rectFillOpacity = relativeExecutionRatio >= 0.05 ? 1.0 : 0.0; } for (const child of treeDescription.allChildren(node)) { colorChildRelativeExecutionRatio(child, executionTime, degreeOfParallelism); } } // Function to add crosslinks between related nodes function addCrosslinks(root: TreeNode): Crosslink[] { interface UnresolvedCrosslink { source: TreeNode; targetName: string; } const unresolvedLinks: UnresolvedCrosslink[] = []; const operatorsByName = new Map<string, TreeNode>(); treeDescription.visitTreeNodes( root, function(node) { // Build map from potential target operator Subplan Name to node const subplanName = node.properties?.get("Subplan Name"); if (subplanName?.startsWith("CTE ")) { operatorsByName.set(subplanName, node); } // Identify source operators if (node.tag === "CTE Scan" && node.properties?.has("CTE Name")) { unresolvedLinks.push({ source: node, targetName: "CTE " + node.properties.get("CTE Name"), }); } }, treeDescription.allChildren, ); // Add crosslinks from source to matching target node const crosslinks = [] as Crosslink[]; for (const link of unresolvedLinks) { const target = operatorsByName.get(link.targetName); if (target !== undefined) { crosslinks.push({source: link.source, target: target}); } } return crosslinks; } // Loads a Postgres query plan export function loadPostgresPlan(json: Json, graphCollapse: unknown = undefined): TreeDescription { // Skip initial array containing a single "Plan" if (Array.isArray(json) && json.length === 1) { json = json[0]; } // Verify Postgres plan signature if (!hasSubOject(json, "Plan") || !hasOwnProperty(json.Plan, "Node Type")) { throw new Error("Invalid Postgres query plan"); } // Load the graph with the nodes collapsed in an automatic way const root = convertPostgres(json, "result"); if (Array.isArray(root)) { throw new Error("Invalid Postgres query plan"); } generateDisplayNames(root); treeDescription.createParentLinks(root); colorForeignScan(root); colorRelativeExecutionTime(root); // Adjust the graph so it is collapsed as requested by the user if (graphCollapse === "y") { treeDescription.visitTreeNodes(root, treeDescription.collapseAllChildren, treeDescription.allChildren); } else if (graphCollapse === "n") { treeDescription.visitTreeNodes(root, treeDescription.expandAllChildren, treeDescription.allChildren); } // Add crosslinks const crosslinks = addCrosslinks(root); return {root: root, crosslinks: crosslinks}; } // Load a JSON tree from text export function loadPostgresPlanFromText(graphString: string, graphCollapse?: unknown): TreeDescription { // Parse the plan as JSON let json: Json; try { json = JSON.parse(graphString); } catch (err) { throw new Error("JSON parse failed with '" + err + "'."); } return loadPostgresPlan(json, graphCollapse); }
the_stack
import { debounce } from '@yeger/debounce' import { select } from 'd3-selection' import type { D3ZoomEvent } from 'd3-zoom' import type { GraphConfig } from 'src/config/config' import type { LinkFilter } from 'src/config/filter' import { defineCanvas, updateCanvasTransform } from 'src/lib/canvas' import { defineDrag } from 'src/lib/drag' import { filterGraph } from 'src/lib/filter' import { createLinks, defineLinkSelection, updateLinks } from 'src/lib/link' import { createMarkers, defineMarkerSelection } from 'src/lib/marker' import { createNodes, defineNodeSelection, updateNodes } from 'src/lib/node' import { defineSimulation } from 'src/lib/simulation' import type { Canvas, Drag, GraphSimulation, LinkSelection, MarkerSelection, NodeSelection, Zoom, } from 'src/lib/types' import { isNumber } from 'src/lib/utils' import { defineZoom } from 'src/lib/zoom' import type { Graph, NodeTypeToken } from 'src/model/graph' import type { GraphLink } from 'src/model/link' import type { GraphNode } from 'src/model/node' import { Vector } from 'vecti' /** * Controller for a graph view. */ export class GraphController< T extends NodeTypeToken = NodeTypeToken, Node extends GraphNode<T> = GraphNode<T>, Link extends GraphLink<T, Node> = GraphLink<T, Node> > { /** * Array of all node types included in the controller's graph. */ public readonly nodeTypes: T[] private _nodeTypeFilter: T[] private _includeUnlinked = true private _linkFilter: LinkFilter<T, Node, Link> = () => true private _showLinkLabels = true private _showNodeLabels = true private filteredGraph!: Graph<T, Node, Link> private width = 0 private height = 0 private simulation: GraphSimulation<T, Node, Link> | undefined private canvas: Canvas | undefined private linkSelection: LinkSelection<T, Node, Link> | undefined private nodeSelection: NodeSelection<T, Node> | undefined private markerSelection: MarkerSelection | undefined private zoom: Zoom | undefined private drag: Drag<T, Node> | undefined private xOffset = 0 private yOffset = 0 private scale: number private focusedNode: Node | undefined = undefined private resizeObserver?: ResizeObserver /** * Create a new controller and initialize the view. * @param container - The container the graph will be placed in. * @param graph - The graph of the controller. * @param config - The config of the controller. */ public constructor( private readonly container: HTMLDivElement, private readonly graph: Graph<T, Node, Link>, private readonly config: GraphConfig<T, Node, Link> ) { this.scale = config.zoom.initial this.resetView() this.graph.nodes.forEach((node) => { const [x, y] = config.positionInitializer( node, this.effectiveWidth, this.effectiveHeight ) node.x = node.x ?? x node.y = node.y ?? y }) this.nodeTypes = [...new Set(graph.nodes.map((d) => d.type))] this._nodeTypeFilter = [...this.nodeTypes] if (config.initial) { const { includeUnlinked, nodeTypeFilter, linkFilter, showLinkLabels, showNodeLabels, } = config.initial this._includeUnlinked = includeUnlinked ?? this._includeUnlinked this._showLinkLabels = showLinkLabels ?? this._showLinkLabels this._showNodeLabels = showNodeLabels ?? this._showNodeLabels this._nodeTypeFilter = nodeTypeFilter ?? this._nodeTypeFilter this._linkFilter = linkFilter ?? this._linkFilter } this.filterGraph(undefined) this.initGraph() this.restart(config.simulation.alphas.initialize) if (config.autoResize) { this.resizeObserver = new ResizeObserver(debounce(() => this.resize())) this.resizeObserver.observe(this.container) } } /** * Get the current node type filter. * Only nodes whose type is included will be shown. */ public get nodeTypeFilter(): T[] { return this._nodeTypeFilter } /** * Get whether nodes without incoming or outgoing links will be shown or not. */ public get includeUnlinked(): boolean { return this._includeUnlinked } /** * Set whether nodes without incoming or outgoing links will be shown or not. * @param value - The value. */ public set includeUnlinked(value: boolean) { this._includeUnlinked = value this.filterGraph(this.focusedNode) const { include, exclude } = this.config.simulation.alphas.filter.unlinked const alpha = value ? include : exclude this.restart(alpha) } /** * Set a new link filter and update the controller's state. * @param value - The new link filter. */ public set linkFilter(value: LinkFilter<T, Node, Link>) { this._linkFilter = value this.filterGraph(this.focusedNode) this.restart(this.config.simulation.alphas.filter.link) } /** * Get the current link filter. * @returns - The current link filter. */ public get linkFilter(): LinkFilter<T, Node, Link> { return this._linkFilter } /** * Get whether node labels are shown or not. */ public get showNodeLabels(): boolean { return this._showNodeLabels } /** * Set whether node labels will be shown or not. * @param value - The value. */ public set showNodeLabels(value: boolean) { this._showNodeLabels = value const { hide, show } = this.config.simulation.alphas.labels.nodes const alpha = value ? show : hide this.restart(alpha) } /** * Get whether link labels are shown or not. */ public get showLinkLabels(): boolean { return this._showLinkLabels } /** * Set whether link labels will be shown or not. * @param value - The value. */ public set showLinkLabels(value: boolean) { this._showLinkLabels = value const { hide, show } = this.config.simulation.alphas.labels.links const alpha = value ? show : hide this.restart(alpha) } private get effectiveWidth(): number { return this.width / this.scale } private get effectiveHeight(): number { return this.height / this.scale } private get effectiveCenter(): Vector { return Vector.of([this.width, this.height]) .divide(2) .subtract(Vector.of([this.xOffset, this.yOffset])) .divide(this.scale) } /** * Resize the graph to fit its container. */ public resize(): void { const oldWidth = this.width const oldHeight = this.height const newWidth = this.container.getBoundingClientRect().width const newHeight = this.container.getBoundingClientRect().height const widthDiffers = oldWidth.toFixed() !== newWidth.toFixed() const heightDiffers = oldHeight.toFixed() !== newHeight.toFixed() if (!widthDiffers && !heightDiffers) { return } this.width = this.container.getBoundingClientRect().width this.height = this.container.getBoundingClientRect().height const alpha = this.config.simulation.alphas.resize this.restart( isNumber(alpha) ? alpha : alpha({ oldWidth, oldHeight, newWidth, newHeight }) ) } /** * Restart the controller. * @param alpha - The alpha value of the controller's simulation after the restart. */ public restart(alpha: number): void { this.markerSelection = createMarkers({ config: this.config, graph: this.filteredGraph, selection: this.markerSelection, }) this.linkSelection = createLinks({ config: this.config, graph: this.filteredGraph, selection: this.linkSelection, showLabels: this._showLinkLabels, }) this.nodeSelection = createNodes({ config: this.config, drag: this.drag, graph: this.filteredGraph, onNodeContext: (d) => this.toggleNodeFocus(d), onNodeSelected: this.config.callbacks.nodeClicked, selection: this.nodeSelection, showLabels: this._showNodeLabels, }) this.simulation?.stop() this.simulation = defineSimulation({ center: () => this.effectiveCenter, config: this.config, graph: this.filteredGraph, onTick: () => this.onTick(), }) .alpha(alpha) .restart() } /** * Update the node type filter by either including or removing the specified type from the filter. * @param include - Whether the type will be included or removed from the filter. * @param nodeType - The type to be added or removed from the filter. */ public filterNodesByType(include: boolean, nodeType: T) { if (include) { this._nodeTypeFilter.push(nodeType) } else { this._nodeTypeFilter = this._nodeTypeFilter.filter( (type) => type !== nodeType ) } this.filterGraph(this.focusedNode) this.restart(this.config.simulation.alphas.filter.type) } /** * Shut down the controller's simulation and (optional) automatic resizing. */ public shutdown(): void { if (this.focusedNode !== undefined) { this.focusedNode.isFocused = false this.focusedNode = undefined } this.resizeObserver?.unobserve(this.container) this.simulation?.stop() } private initGraph(): void { this.zoom = defineZoom({ config: this.config, canvasContainer: () => select(this.container).select('svg'), min: this.config.zoom.min, max: this.config.zoom.max, onZoom: (event) => this.onZoom(event), }) this.canvas = defineCanvas({ applyZoom: this.scale !== 1, container: select(this.container), offset: [this.xOffset, this.yOffset], scale: this.scale, zoom: this.zoom, }) this.applyZoom() this.linkSelection = defineLinkSelection(this.canvas) this.nodeSelection = defineNodeSelection(this.canvas) this.markerSelection = defineMarkerSelection(this.canvas) this.drag = defineDrag({ config: this.config, onDragStart: () => this.simulation ?.alphaTarget(this.config.simulation.alphas.drag.start) .restart(), onDragEnd: () => this.simulation ?.alphaTarget(this.config.simulation.alphas.drag.end) .restart(), }) } private onTick(): void { updateNodes(this.nodeSelection) updateLinks({ config: this.config, center: this.effectiveCenter, graph: this.filteredGraph, selection: this.linkSelection, }) } private resetView(): void { this.simulation?.stop() select(this.container).selectChildren().remove() this.zoom = undefined this.canvas = undefined this.linkSelection = undefined this.nodeSelection = undefined this.markerSelection = undefined this.simulation = undefined this.width = this.container.getBoundingClientRect().width this.height = this.container.getBoundingClientRect().height } private onZoom(event: D3ZoomEvent<SVGSVGElement, undefined>): void { this.xOffset = event.transform.x this.yOffset = event.transform.y this.scale = event.transform.k this.applyZoom() this.simulation?.restart() } private applyZoom() { updateCanvasTransform({ canvas: this.canvas, scale: this.scale, xOffset: this.xOffset, yOffset: this.yOffset, }) } private toggleNodeFocus(node: Node): void { if (node.isFocused) { this.filterGraph(undefined) this.restart(this.config.simulation.alphas.focus.release(node)) } else { this.focusNode(node) } } private focusNode(node: Node): void { this.filterGraph(node) this.restart(this.config.simulation.alphas.focus.acquire(node)) } private filterGraph(nodeToFocus?: Node): void { if (this.focusedNode !== undefined) { this.focusedNode.isFocused = false this.focusedNode = undefined } if ( nodeToFocus !== undefined && this._nodeTypeFilter.includes(nodeToFocus.type) ) { nodeToFocus.isFocused = true this.focusedNode = nodeToFocus } this.filteredGraph = filterGraph({ graph: this.graph, filter: this._nodeTypeFilter, focusedNode: this.focusedNode, includeUnlinked: this._includeUnlinked, linkFilter: this._linkFilter, }) } }
the_stack
import action from "../../src/actionCreators/actions"; import map from "../../src/mappers/actionToHostMessage"; import { should } from "chai"; import ServiceError from "../../src/ServiceError"; import { IInstrumentation } from "../../src/IState"; import { defaultGistProject } from "../testResources"; import { CREATE_OPERATION_ID_RESPONSE, CREATE_PROJECT_RESPONSE, CREATE_REGIONS_FROM_SOURCEFILES_RESPONSE } from "../../src/constants/ApiMessageTypes"; describe("actionToHostMessage mapper", function () { // default case handling it("returns empty for not supported messages with requestId", function () { var result = map(action.runRequest("testRun"), "https://try.dot.net", "editorId"); should().not.exist(result); }); it("returns empty for not supported messages", function () { var result = map(action.loadCodeRequest(""), "https://try.dot.net", "editorId"); should().not.exist(result); }); // API usages events it("maps RUN_CLICKED to RunStarted message", function () { var expectedResult = { type: "RunStarted", messageOrigin: "https://try.dot.net" }; var result = map(action.runClicked(), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps UPDATE_WORKSPACE_BUFFER to CodeModified message", function () { var expectedResult = { sourceCode: "foo()", editorId: "editorId", type: "CodeModified", bufferId: "Program.cs", messageOrigin: "https://try.dot.net" }; var result = map(action.updateWorkspaceBuffer("foo()", "Program.cs"), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps NOTIFY_HOST_LISTENER_READY to HostListenerReady message", function () { var expectedResult = { type: "HostListenerReady", messageOrigin: "https://try.dot.net", editorId: "listenerA" }; var result = map(action.hostListenerReady("listenerA"), "https://try.dot.net", null); result.should.deep.equal(expectedResult); }); it("maps NOTIFY_HOST_RUN_READY to HostRunReady message", function () { var expectedResult = { type: "HostRunReady", messageOrigin: "https://try.dot.net", editorId: "listenerA" }; var result = map(action.hostRunReady("listenerA"), "https://try.dot.net", null); result.should.deep.equal(expectedResult); }); it("maps NOTIFY_HOST_EDITOR_READY to HostEditorReady message", function () { var expectedResult = { type: "HostEditorReady", messageOrigin: "https://try.dot.net", editorId: "listenerA" }; var result = map(action.hostEditorReady("listenerA"), "https://try.dot.net", null); result.should.deep.equal(expectedResult); }); it("maps WASMRUNNER_READY to HostListenerReady message", function () { var expectedResult = { type: "HostListenerReady", messageOrigin: "https://try.dot.net", editorId: "listenerA" }; var result = map(action.wasmRunnerReady("listenerA"), "https://try.dot.net", null); result.should.deep.equal(expectedResult); }); it("maps NOTIFY_MONACO_READY to MonacoEditorReady message", function () { var expectedResult = { type: "MonacoEditorReady", messageOrigin: "https://try.dot.net" }; var result = map(action.notifyMonacoReady({ focus: () => { }, layout: () => { } }), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); // user events it("maps RUN_CODE_SUCCESS to RunCompleted message with outcome: 'Success'", function () { var expectedResult = { type: "RunCompleted", outcome: "Success", output: ["some", "lines"], messageOrigin: "https://try.dot.net" }; var result = map(action.runSuccess({ output: ["some", "lines"], succeeded: true }), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps RUN_CODE_SUCCESS to RunCompleted message with outcome: 'CompilationError'", function () { var expectedResult = { type: "RunCompleted", outcome: "CompilationError", output: ["some", "lines"], messageOrigin: "https://try.dot.net" }; var result = map(action.runSuccess({ output: ["some", "lines"], succeeded: false }), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps RUN_CODE_SUCCESS to RunCompleted message with outcome: 'Exception'", function () { var expectedResult = { type: "RunCompleted", exception: "some exception with stack trace", outcome: "Exception", output: ["some", "lines"], messageOrigin: "https://try.dot.net" }; var result = map(action.runSuccess({ exception: "some exception with stack trace", output: ["some", "lines"], succeeded: false }), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps RUN_CODE_SUCCESS with instrumentation to RunCompleted with instrumentation and without output", () => { map(action.runSuccess({ output: ["something"], succeeded: true, instrumentation: [] as IInstrumentation[] }), "https://try.dot.net", "editorId").should.deep.equal({ type: "RunCompleted", outcome: "Success", instrumentation: true, messageOrigin: "https://try.dot.net" }); }); // system errors it("maps LOAD_CODE_FAILURE to LoadCodeFailed message", function () { var expectedResult = { type: "LoadCodeFailed", messageOrigin: "https://try.dot.net" }; var result = map(action.loadCodeFailure(new Error("900")), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); it("maps RUN_CODE_FAILURE to ServiceError message with outcome: 'Exception'", function () { var expectedResult = { type: "ServiceError", statusCode: 503, message: "Service Unavailable", requestId: "123456", messageOrigin: "https://try.dot.net" }; var result = map(action.runFailure(new ServiceError(503, "Service Unavailable", "123456")), "https://try.dot.net", "editorId"); result.should.deep.equal(expectedResult); }); // instrumentation it("maps OUTPUT_UPDATED to OutpuUpdated with output", () => { map(action.outputUpdated(["expected"]), "https://try.dot.net", "editorId") .should.deep.equal({ type: "OutputUpdated", output: ["expected"], messageOrigin: "https://try.dot.net" }); }); it("maps CANNOT_MOVE_NEXT to CanMoveNext with value false", () => { map(action.cannotMoveNext(), "https://try.dot.net", "editorId") .should.deep.equal({ type: "CanMoveNext", value: false, messageOrigin: "https://try.dot.net" }); }); it("maps CAN_MOVE_NEXT to CanMoveNext with value true", () => { map(action.canMoveNext(), "https://try.dot.net", "editorId") .should.deep.equal({ type: "CanMoveNext", value: true, messageOrigin: "https://try.dot.net" }); }); it("maps CANNOT_MOVE_PREV to CanMovePrev with value false", () => { map(action.cannotMovePrev(), "https://try.dot.net", "editorId") .should.deep.equal({ type: "CanMovePrev", value: false, messageOrigin: "https://try.dot.net" }); }); it("maps CAN_MOVE_PREV to CanMovePrev with value true", () => { map(action.canMovePrev(), "https://try.dot.net", "editorId") .should.deep.equal({ type: "CanMovePrev", value: true, messageOrigin: "https://try.dot.net" }); }); it("maps OPERATION_ID_GENERATED to OperationIdGenerated", () => { let message = map(action.generateOperationId("Test_Run"), "https://try.dot.net", "editorId"); message.type.should.equal(CREATE_OPERATION_ID_RESPONSE); message.requestId.should.equal("Test_Run"); message.operationId.should.not.equal(null); }); it("maps CREATE_PROJECT_FAILURE to createprojectresponse with success set to false", () => { let message = map(action.projectCreationFailure(new Error("general"), "Test_Run"), "https://try.dot.net", "editorId"); message.type.should.equal(CREATE_PROJECT_RESPONSE); message.requestId.should.equal("Test_Run"); message.success.should.be.equal(false); }); it("maps CREATE_PROJECT_SUCCESS to createprojectresponse with success set to true", () => { let message = map(action.projectCreationSuccess({ requestId: "Test_Run", project: { ...defaultGistProject } }), "https://try.dot.net", "editorId"); message.type.should.equal(CREATE_PROJECT_RESPONSE); message.requestId.should.equal("Test_Run"); message.success.should.be.equal(true); message.project.should.not.be.equal(null); }); it("maps GENERATE_REGIONS_FROM_FILES_FAILURE to generateregionfromfilesresponse with success set to false", () => { let message = map(action.createRegionsFromProjectFilesFailure(new Error("general"), "Test_Run"), "https://try.dot.net", "editorId"); message.type.should.equal(CREATE_REGIONS_FROM_SOURCEFILES_RESPONSE); message.requestId.should.equal("Test_Run"); message.success.should.be.equal(false); }); it("maps GENERATE_REGIONS_FROM_FILES_SUCCESS to generateregionfromfilesresponse with success set to true", () => { let message = map(action.createRegionsFromProjectFilesSuccess({ requestId: "Test_Run", regions: [{ id: "code.cs", content: "code here" }] }), "https://try.dot.net", "editorId"); message.type.should.equal(CREATE_REGIONS_FROM_SOURCEFILES_RESPONSE); message.requestId.should.equal("Test_Run"); message.success.should.be.equal(true); message.regions[0].id.should.be.equal("code.cs"); message.regions[0].content.should.be.equal("code here"); }); });
the_stack
export class SVGFilters { public flood(filter: SVGFilterElement, resultId: string, color: string, opacity: number, _settings?: any): void { const floodElement = document.createElementNS("http://www.w3.org/2000/svg", "feFlood"); if (resultId) { floodElement.setAttribute("id", resultId); } floodElement.setAttribute("flood-color", color); floodElement.setAttribute("flood-opacity", opacity.toString()); filter.appendChild(floodElement); } public composite(filter: SVGFilterElement, resultId: string, in1: string, in2: string, k1?: number, k2?: number, k3?: number, k4?: number, _settings?: any): void { const compositeElement = document.createElementNS("http://www.w3.org/2000/svg", "feComposite"); if (resultId) { compositeElement.setAttribute("id", resultId); } compositeElement.setAttribute("in", in1); compositeElement.setAttribute("in2", in2); filter.appendChild(compositeElement); } } export class SVGPathBuilder { private _path = ""; public move(x: number, y: number): void { this._path += ` M ${x} ${y}`; } public path(): string { return this._path.substr(1); } public line(pts: number[][]): void { pts.forEach((point) => { this._path += ` L ${point[0]} ${point[1]}`; }); } public curveC(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void { this._path += ` C ${x1} ${y1}, ${x2} ${y2}, ${x} ${y}`; } public close(): void { this._path += ` Z`; } } export class SVG { public filters = new SVGFilters(); private _svg: SVGElement; private _defs: SVGDefsElement | undefined = undefined; constructor(svg: SVGElement) { this._svg = svg; } public svg(parent: Element, x: number, y: number, width: number, height: number, settings?: any): SVGElement { const svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svgElement.setAttribute("x", x.toString()); svgElement.setAttribute("y", y.toString()); svgElement.setAttribute("width", width.toString()); svgElement.setAttribute("height", height.toString()); this._appendSettings(settings, svgElement); if (parent != null) { parent.appendChild(svgElement); } else { this._svg.appendChild(svgElement); } return svgElement; } public image(parent: Element, x: number, y: number, width: number, height: number, url: string, settings?: any): SVGImageElement { const imageElement = document.createElementNS("http://www.w3.org/2000/svg", "image"); imageElement.setAttribute("x", x.toString()); imageElement.setAttribute("y", y.toString()); imageElement.setAttribute("width", width.toString()); imageElement.setAttribute("height", height.toString()); imageElement.setAttributeNS("http://www.w3.org/1999/xlink", "href", url); this._appendSettings(settings, imageElement); parent.appendChild(imageElement); return imageElement; } public rect(parent: Element, x: number, y: number, width: number, height: number, rx?: number, ry?: number, settings?: any): SVGRectElement; public rect(parent: Element, x: number, y: number, width: number, height: number, settings?: any): SVGRectElement; public rect(parent: Element, x: number, y: number, width: number, height: number, rx?: number | any, ry?: number, settings?: any): SVGRectElement { const rectElement = document.createElementNS("http://www.w3.org/2000/svg", "rect"); rectElement.setAttribute("x", x.toString()); rectElement.setAttribute("y", y.toString()); rectElement.setAttribute("width", width.toString()); rectElement.setAttribute("height", height.toString()); if (rx !== undefined) { if (rx instanceof Number) { rectElement.setAttribute("rx", rx.toString()); } else if (rx instanceof Object) { this._appendSettings(rx, rectElement); } } if (ry !== undefined) { rectElement.setAttribute("ry", ry.toString()); } this._appendSettings(settings, rectElement); parent.appendChild(rectElement); return rectElement; } public line(parent: Element, x1: number, y1: number, x2: number, y2: number, settings?: any): SVGLineElement { const lineElement = document.createElementNS("http://www.w3.org/2000/svg", "line"); lineElement.setAttribute("x1", x1.toString()); lineElement.setAttribute("y1", y1.toString()); lineElement.setAttribute("x2", x2.toString()); lineElement.setAttribute("y2", y2.toString()); this._appendSettings(settings, lineElement); parent.appendChild(lineElement); return lineElement; } public polygon(parent: Element, points: number[][], settings?: any): SVGPolygonElement { const polygonElement = document.createElementNS("http://www.w3.org/2000/svg", "polygon"); polygonElement.setAttribute("points", points.map((point) => point.join(",")).join(" ")); this._appendSettings(settings, polygonElement); parent.appendChild(polygonElement); return polygonElement; } public polyline(parent: Element, points: number[][], settings?: any): SVGPolylineElement { const polylineElement = document.createElementNS("http://www.w3.org/2000/svg", "polyline"); polylineElement.setAttribute("points", points.map((point) => point.join(",")).join(" ")); this._appendSettings(settings, polylineElement); parent.appendChild(polylineElement); return polylineElement; } public ellipse(parent: Element, cx: number, cy: number, rx: number, ry: number, settings?: any): SVGEllipseElement { const ellipseElement = document.createElementNS("http://www.w3.org/2000/svg", "ellipse"); ellipseElement.setAttribute("cx", cx.toString()); ellipseElement.setAttribute("cy", cy.toString()); ellipseElement.setAttribute("rx", rx.toString()); ellipseElement.setAttribute("ry", ry.toString()); this._appendSettings(settings, ellipseElement); parent.appendChild(ellipseElement); return ellipseElement; } public path(parent: SVGElement, builder: SVGPathBuilder, settings?: any): SVGPathElement { const pathElement = document.createElementNS("http://www.w3.org/2000/svg", "path"); pathElement.setAttribute("d", builder.path()); this._appendSettings(settings, pathElement); parent.appendChild(pathElement); return pathElement; } public text(parent: Element, x: number, y: number, value: string, settings?: any): SVGTextElement { const textElement = document.createElementNS("http://www.w3.org/2000/svg", "text"); textElement.setAttribute("x", x.toString()); textElement.setAttribute("y", y.toString()); this._appendSettings(settings, textElement); const textNode = document.createTextNode(value); textElement.appendChild(textNode); parent.appendChild(textElement); return textElement; } public filter(parent: Element, id: string, x: number, y: number, width: number, height: number, settings?: any): SVGFilterElement { const filterElement = document.createElementNS("http://www.w3.org/2000/svg", "filter"); filterElement.setAttribute("x", x.toString()); filterElement.setAttribute("y", y.toString()); filterElement.setAttribute("width", width.toString()); filterElement.setAttribute("height", height.toString()); this._appendSettings(settings, filterElement); parent.appendChild(filterElement); return filterElement; } public pattern(parent: Element, resultId: string, x: number, y: number, width: number, height: number, settings?: any): SVGPatternElement { const patternElement = document.createElementNS("http://www.w3.org/2000/svg", "pattern"); if (resultId) { patternElement.setAttribute("id", resultId); } patternElement.setAttribute("x", x.toString()); patternElement.setAttribute("y", y.toString()); patternElement.setAttribute("width", width.toString()); patternElement.setAttribute("height", height.toString()); this._appendSettings(settings, patternElement); parent.appendChild(patternElement); return patternElement; } public defs(): SVGDefsElement { if (this._defs === undefined) { const defsElement = document.createElementNS("http://www.w3.org/2000/svg", "defs"); this._svg.appendChild(defsElement); this._defs = defsElement; } return this._defs; } public clipPath(parent: Element, resultId: string, units?: string, settings?: any): SVGClipPathElement { const clipElement = document.createElementNS("http://www.w3.org/2000/svg", "clipPath"); if (resultId) { clipElement.setAttribute("id", resultId); } if (units === undefined) { units = "userSpaceOnUse"; } clipElement.setAttribute("clipPathUnits", units); this._appendSettings(settings, clipElement); parent.appendChild(clipElement); return clipElement; } public createPath(): SVGPathBuilder { return new SVGPathBuilder(); } private _appendSettings(settings: any | undefined, element: Element): void { if (settings !== undefined) { Object.keys(settings).forEach((key) => { element.setAttribute(key, settings[key]); }); } } }
the_stack
* #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import JoynrMessage from "../../../../main/js/joynr/messaging/JoynrMessage"; import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos"; import * as MessagingQosEffort from "../../../../main/js/joynr/messaging/MessagingQosEffort"; import * as OneWayRequest from "../../../../main/js/joynr/dispatching/types/OneWayRequest"; import * as Request from "../../../../main/js/joynr/dispatching/types/Request"; import * as Reply from "../../../../main/js/joynr/dispatching/types/Reply"; import BroadcastSubscriptionRequest from "../../../../main/js/joynr/dispatching/types/BroadcastSubscriptionRequest"; import MulticastSubscriptionRequest from "../../../../main/js/joynr/dispatching/types/MulticastSubscriptionRequest"; import SubscriptionRequest from "../../../../main/js/joynr/dispatching/types/SubscriptionRequest"; import SubscriptionReply from "../../../../main/js/joynr/dispatching/types/SubscriptionReply"; import SubscriptionStop from "../../../../main/js/joynr/dispatching/types/SubscriptionStop"; import * as MulticastPublication from "../../../../main/js/joynr/dispatching/types/MulticastPublication"; import * as SubscriptionPublication from "../../../../main/js/joynr/dispatching/types/SubscriptionPublication"; import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton"; import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import Version from "../../../../main/js/generated/joynr/types/Version"; import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos"; import nanoid from "nanoid"; import TestEnum from "../../../generated/joynr/tests/testTypes/TestEnum"; import Dispatcher from "../../../../main/js/joynr/dispatching/Dispatcher"; import testUtil = require("../../testUtil"); import SubscriptionQos from "../../../../main/js/joynr/proxy/SubscriptionQos"; const providerId = "providerId"; const proxyId = "proxyId"; let toDiscoveryEntry: any, globalToDiscoveryEntry: any; describe("libjoynr-js.joynr.dispatching.Dispatcher", () => { let dispatcher: Dispatcher, requestReplyManager: any, subscriptionManager: any, publicationManager: any, messageRouter: any, clusterControllerMessagingStub: any, securityManager: any; const subscriptionId = `mySubscriptionId-${nanoid()}`; const multicastId = `multicastId-${nanoid()}`; const requestReplyId = "requestReplyId"; /** * Called before each test. */ beforeEach(() => { toDiscoveryEntry = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }), domain: "testProviderDomain", interfaceName: "interfaceName", participantId: providerId, qos: new ProviderQos(undefined as any), lastSeenDateMs: Date.now(), expiryDateMs: Date.now() + 60000, publicKeyId: "publicKeyId", isLocal: true }); globalToDiscoveryEntry = new DiscoveryEntryWithMetaInfo(toDiscoveryEntry); globalToDiscoveryEntry.isLocal = false; requestReplyManager = { handleOneWayRequest: jest.fn(), handleRequest: jest.fn(), handleReply: jest.fn() }; subscriptionManager = { handleSubscriptionReply: jest.fn(), handleMulticastPublication: jest.fn(), handlePublication: jest.fn() }; function sendSubscriptionReply( _proxyParticipantId: string, _providerParticipantId: string, subscriptionRequest: any, callbackDispatcher: Function, callbackDispatcherSettings: any ) { callbackDispatcher( callbackDispatcherSettings, new SubscriptionReply({ subscriptionId: subscriptionRequest.subscriptionId }) ); } publicationManager = { handleSubscriptionRequest: sendSubscriptionReply, handleMulticastSubscriptionRequest: sendSubscriptionReply, handleSubscriptionStop() {} }; jest.spyOn(publicationManager, "handleSubscriptionRequest"); jest.spyOn(publicationManager, "handleMulticastSubscriptionRequest"); jest.spyOn(publicationManager, "handleSubscriptionStop"); messageRouter = { addMulticastReceiver: jest.fn(), removeMulticastReceiver: jest.fn() }; messageRouter.addMulticastReceiver.mockReturnValue(Promise.resolve()); clusterControllerMessagingStub = { transmit: jest.fn() }; clusterControllerMessagingStub.transmit.mockReturnValue(Promise.resolve()); securityManager = { getCurrentProcessUserId: jest.fn() }; dispatcher = new Dispatcher(clusterControllerMessagingStub, securityManager); dispatcher.registerRequestReplyManager(requestReplyManager); dispatcher.registerSubscriptionManager(subscriptionManager); dispatcher.registerPublicationManager(publicationManager); dispatcher.registerMessageRouter(messageRouter); TypeRegistrySingleton.getInstance().addType(TestEnum); }); it("is instantiable and of correct type", () => { expect(Dispatcher).toBeDefined(); expect(typeof Dispatcher === "function").toBeTruthy(); expect(dispatcher).toBeDefined(); expect(dispatcher).toBeInstanceOf(Dispatcher); expect(dispatcher.registerRequestReplyManager).toBeDefined(); expect(typeof dispatcher.registerRequestReplyManager === "function").toBeTruthy(); expect(dispatcher.registerSubscriptionManager).toBeDefined(); expect(typeof dispatcher.registerSubscriptionManager === "function").toBeTruthy(); expect(dispatcher.registerPublicationManager).toBeDefined(); expect(typeof dispatcher.registerPublicationManager === "function").toBeTruthy(); expect(dispatcher.sendRequest).toBeDefined(); expect(typeof dispatcher.sendRequest === "function").toBeTruthy(); expect(dispatcher.sendOneWayRequest).toBeDefined(); expect(typeof dispatcher.sendOneWayRequest === "function").toBeTruthy(); expect(dispatcher.sendBroadcastSubscriptionRequest).toBeDefined(); expect(typeof dispatcher.sendBroadcastSubscriptionRequest === "function").toBeTruthy(); expect(dispatcher.sendSubscriptionRequest).toBeDefined(); expect(typeof dispatcher.sendSubscriptionRequest === "function").toBeTruthy(); expect(dispatcher.sendSubscriptionStop).toBeDefined(); expect(typeof dispatcher.sendSubscriptionStop === "function").toBeTruthy(); expect(dispatcher.sendPublication).toBeDefined(); expect(typeof dispatcher.sendPublication === "function").toBeTruthy(); expect(dispatcher.receive).toBeDefined(); expect(typeof dispatcher.receive === "function").toBeTruthy(); }); function receiveJoynrMessage(parameters: any) { const joynrMessage = new JoynrMessage({ type: parameters.type, payload: JSON.stringify(parameters.payload) }); joynrMessage.from = proxyId; joynrMessage.to = providerId; dispatcher.receive(joynrMessage); } it("forwards subscription request to Publication Manager", () => { const payload = { subscribedToName: "attributeName", subscriptionId }; receiveJoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST, payload }); expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalled(); expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalledWith( proxyId, providerId, new SubscriptionRequest(payload as any), expect.any(Function), expect.any(Object) ); }); it("forwards multicast subscription request to Publication Manager", () => { const payload = { subscribedToName: "multicastEvent", subscriptionId, multicastId }; receiveJoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST, payload }); expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalled(); expect(publicationManager.handleMulticastSubscriptionRequest).toHaveBeenCalledWith( proxyId, providerId, new MulticastSubscriptionRequest(payload), expect.any(Function), expect.any(Object) ); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.payload).toMatch( `{"_typeName":"joynr.SubscriptionReply","subscriptionId":"${subscriptionId}"}` ); }); it("forwards subscription reply to Subscription Manager", () => { const payload = { subscriptionId }; const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY, payload: JSON.stringify(payload) }); dispatcher.receive(joynrMessage); expect(subscriptionManager.handleSubscriptionReply).toHaveBeenCalled(); expect(subscriptionManager.handleSubscriptionReply).toHaveBeenCalledWith(new SubscriptionReply(payload)); }); it("forwards subscription stop to SubscriptionPublication Manager", () => { const payload = { subscriptionId }; const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP, payload: JSON.stringify(payload) }); dispatcher.receive(joynrMessage); expect(publicationManager.handleSubscriptionStop).toHaveBeenCalled(); expect(publicationManager.handleSubscriptionStop).toHaveBeenCalledWith(new SubscriptionStop(payload)); }); function receivePublication(parameters: any) { const joynrMessage = new JoynrMessage({ type: parameters.type, payload: JSON.stringify(parameters.payload) }); dispatcher.receive(joynrMessage); } it("forwards publication to Subscription Manager", () => { const payload = { subscriptionId, response: "myResponse" }; receivePublication({ type: JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION, payload }); expect(subscriptionManager.handlePublication).toHaveBeenCalled(); expect(subscriptionManager.handlePublication).toHaveBeenCalledWith(SubscriptionPublication.create(payload)); }); it("forwards multicast publication to Subscription Manager", () => { const payload = { multicastId, response: "myResponse" }; receivePublication({ type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST, payload }); expect(subscriptionManager.handleMulticastPublication).toHaveBeenCalled(); expect(subscriptionManager.handleMulticastPublication).toHaveBeenCalledWith( MulticastPublication.create(payload) ); }); it("forwards request to RequestReply Manager", () => { const request = Request.create({ methodName: "methodName" }); const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, payload: JSON.stringify(request) }); joynrMessage.to = providerId; joynrMessage.from = proxyId; dispatcher.receive(joynrMessage); expect(requestReplyManager.handleRequest).toHaveBeenCalled(); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][0]).toEqual(providerId); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][1]).toEqual(request); }); it("forwards one-way request to RequestReply Manager", () => { const oneWayRequest = OneWayRequest.create({ methodName: "methodName" }); const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY, payload: JSON.stringify(oneWayRequest) }); joynrMessage.to = providerId; joynrMessage.from = proxyId; dispatcher.receive(joynrMessage); expect(requestReplyManager.handleOneWayRequest).toHaveBeenCalled(); expect(requestReplyManager.handleOneWayRequest.mock.calls.slice(-1)[0][0]).toEqual(providerId); expect(requestReplyManager.handleOneWayRequest.mock.calls.slice(-1)[0][1]).toEqual(oneWayRequest); }); it("forwards reply to RequestReply Manager", () => { const reply = Reply.create({ requestReplyId, response: [] }); const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REPLY, payload: JSON.stringify(reply) }); dispatcher.receive(joynrMessage); expect(requestReplyManager.handleReply).toHaveBeenCalled(); expect(requestReplyManager.handleReply).toHaveBeenCalledWith(reply); }); function sendBroadcastSubscriptionRequest(request: Request) { const messagingQos = new MessagingQos(); return dispatcher.sendBroadcastSubscriptionRequest({ from: proxyId, toDiscoveryEntry, messagingQos, subscriptionRequest: request as any }); } it("does not send multicast subscription request if addMulticastReceiver fails", async () => { const multicastId = "multicastId"; const multicastSubscriptionRequest = new MulticastSubscriptionRequest({ subscribedToName: "multicastEvent", subscriptionId: "subscriptionId", multicastId }); messageRouter.addMulticastReceiver.mockReturnValue(Promise.reject()); expect(messageRouter.addMulticastReceiver).not.toHaveBeenCalled(); expect(clusterControllerMessagingStub.transmit).not.toHaveBeenCalled(); await testUtil.reversePromise(sendBroadcastSubscriptionRequest(multicastSubscriptionRequest as any)); expect(messageRouter.addMulticastReceiver).toHaveBeenCalledTimes(1); expect(clusterControllerMessagingStub.transmit).not.toHaveBeenCalled(); }); it("is able to send selective broadcast subscription request", () => { expect(clusterControllerMessagingStub.transmit).not.toHaveBeenCalled(); const broadcastSubscriptionRequest = new BroadcastSubscriptionRequest({ subscribedToName: "broadcastEvent", subscriptionId: "subscriptionId" } as any); const serializedPayload = JSON.stringify(broadcastSubscriptionRequest); sendBroadcastSubscriptionRequest(broadcastSubscriptionRequest as any); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalledTimes(1); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.type).toEqual(JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST); expect(sentMessage.from).toEqual(proxyId); expect(sentMessage.to).toEqual(providerId); expect(sentMessage.payload).toEqual(serializedPayload); }); it("sets isLocalMessage in request messages", () => { let sentMessage: any; const messagingQos = new MessagingQos(); const request = Request.create({ methodName: "methodName" }); dispatcher.sendRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.isLocalMessage).toEqual(true); dispatcher.sendRequest({ from: "from", toDiscoveryEntry: globalToDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.isLocalMessage).toEqual(false); }); it("sets compress in request messages", () => { let sentMessage: any; const messagingQos = new MessagingQos(); messagingQos.compress = true; const request = Request.create({ methodName: "methodName" }); dispatcher.sendRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.isLocalMessage).toEqual(true); dispatcher.sendRequest({ from: "from", toDiscoveryEntry: globalToDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.compress).toEqual(true); }); function verifyEffortForReply(request: any, expectedEffort: any) { expect(requestReplyManager.handleRequest).toHaveBeenCalled(); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][0]).toEqual(providerId); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][1]).toEqual(request); expect(clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0].effort).toEqual(expectedEffort); requestReplyManager.handleRequest.mockClear(); clusterControllerMessagingStub.transmit.mockClear(); } it("sets the correct effort for replies if the effort was set in the corresponding request", async () => { const request = Request.create({ methodName: "methodName" }); const joynrMessage: any = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, payload: JSON.stringify(request) }); joynrMessage.to = providerId; joynrMessage.from = proxyId; joynrMessage.compress = true; requestReplyManager.handleRequest.mockImplementation( (_to: any, request: Request, cb: any, replySettings: any) => { cb(replySettings, request); return Promise.resolve(); } ); joynrMessage.effort = undefined; // default await dispatcher.receive(joynrMessage); verifyEffortForReply(request, undefined); joynrMessage.effort = MessagingQosEffort.NORMAL.value; await dispatcher.receive(joynrMessage); verifyEffortForReply(request, undefined); joynrMessage.effort = MessagingQosEffort.BEST_EFFORT.value; await dispatcher.receive(joynrMessage); verifyEffortForReply(request, MessagingQosEffort.BEST_EFFORT.value); joynrMessage.effort = "INVALID_EFFORT"; await dispatcher.receive(joynrMessage); verifyEffortForReply(request, undefined); }); it("sets the compressed flag for replies if the request was compressed", async () => { const request = Request.create({ methodName: "methodName" }); const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST, payload: JSON.stringify(request) }); joynrMessage.to = providerId; joynrMessage.from = proxyId; joynrMessage.compress = true; requestReplyManager.handleRequest.mockImplementation( (_to: any, request: Request, cb: any, replySettings: any) => { cb(replySettings, request); return Promise.resolve(); } ); await dispatcher.receive(joynrMessage); expect(requestReplyManager.handleRequest).toHaveBeenCalled(); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][0]).toEqual(providerId); expect(requestReplyManager.handleRequest.mock.calls.slice(-1)[0][1]).toEqual(request); expect(clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0].compress).toBe(true); }); it("enriches requests with custom headers", () => { const request = Request.create({ methodName: "methodName" }); const messagingQos = new MessagingQos(); const headerKey = "key"; const headerValue = "value"; messagingQos.putCustomMessageHeader(headerKey, headerValue); dispatcher.sendRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.getCustomHeaders()[headerKey]).toEqual(headerValue); expect(sentMessage.getCustomHeaders()["z4"]).toEqual(request.requestReplyId); }); it("enriches requests with effort header", () => { const request = Request.create({ methodName: "methodName" }); const messagingQos = new MessagingQos(); messagingQos.effort = MessagingQosEffort.BEST_EFFORT; dispatcher.sendRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.effort).toEqual(MessagingQosEffort.BEST_EFFORT.value); }); it("enriches one way requests with custom headers", () => { const request = OneWayRequest.create({ methodName: "methodName" }); const messagingQos = new MessagingQos(); const headerKey = "key"; const headerValue = "value"; messagingQos.putCustomMessageHeader(headerKey, headerValue); dispatcher.sendOneWayRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.getCustomHeaders()[headerKey]).toEqual(headerValue); expect(sentMessage.getCustomHeaders()["z4"]).toEqual(undefined); }); it("enriches replies with custom headers from request", async () => { const request = Request.create({ methodName: "methodName" }); const messagingQos = new MessagingQos(); const headerKey = "key"; const headerValue = "value"; messagingQos.putCustomMessageHeader(headerKey, headerValue); dispatcher.sendRequest({ from: "from", toDiscoveryEntry, messagingQos, request }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentRequestMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; const clusterControllerMessagingStubTransmitCallsCount = clusterControllerMessagingStub.transmit.mock.calls.length; // get ready for an incoming request: when handleRequest is called, pass an empty reply back. requestReplyManager.handleRequest.mockImplementation( (_to: any, request: Request, cb: any, replySettings: any) => { cb(replySettings, request); return Promise.resolve(); } ); await dispatcher.receive(sentRequestMessage); const sentReplyMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(clusterControllerMessagingStub.transmit.mock.calls.length).toBe( clusterControllerMessagingStubTransmitCallsCount + 1 ); expect(sentReplyMessage.getCustomHeaders()[headerKey]).toEqual(headerValue); expect(sentReplyMessage.getCustomHeaders()["z4"]).toEqual(request.requestReplyId); }); it("sends subscription reply on subscription request", async () => { const payload = { subscribedToName: "attributeName", subscriptionId }; const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST, payload: JSON.stringify(payload) }); joynrMessage.from = proxyId; joynrMessage.to = providerId; const subscriptionReply = new SubscriptionReply(payload); /* * The dispatcher.receive() based on the message type calls * publicationManager.handleSubscriptionRequest() * and hands over a callback that invokes sendSubscriptionReply(). * The resulting message is finally sent out using * clusterControllerMessagingStub.transmit(). */ publicationManager.handleSubscriptionRequest.mockImplementation( ( _proxyId: any, _providerId: any, _subscriptionRequest: SubscriptionRequest, callback: any, settings: any ) => { callback(settings, subscriptionReply); } ); await dispatcher.receive(joynrMessage); /* * Note: We can directly expect stuff here only just because * the jasmine spies do not emulate async action which would * otherwise occur in real code. */ expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalled(); expect(publicationManager.handleSubscriptionRequest).toHaveBeenCalledWith( proxyId, providerId, new SubscriptionRequest(payload as any), expect.any(Function), expect.any(Object) ); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalled(); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls.slice(-1)[0][0]; expect(sentMessage.type).toEqual(JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY); expect(sentMessage.payload).toEqual(JSON.stringify(subscriptionReply)); }); it("accepts messages with Parse Errors", async () => { const joynrMessage = new JoynrMessage({ type: JoynrMessage.JOYNRMESSAGE_TYPE_REPLY, payload: "invalidJSONPayload[/}" }); await dispatcher.receive(joynrMessage); }); function checkZ4Header(expectedHeader: any): void { expect(clusterControllerMessagingStub.transmit).toHaveBeenCalledTimes(1); const sentMessage = clusterControllerMessagingStub.transmit.mock.calls[0][0]; expect(sentMessage.getCustomHeaders()["z4"]).toEqual(expectedHeader); clusterControllerMessagingStub.transmit.mockClear(); } it("check z4 header for different variants of requests", async () => { // subscriptionRequest const subscriptionRequestId = "testSubscriptionRequestId"; const subscriptionRequest = new SubscriptionRequest({ subscribedToName: "attributeName", subscriptionId: subscriptionRequestId, qos: new SubscriptionQos() }); await dispatcher.sendSubscriptionRequest({ from: proxyId, toDiscoveryEntry, messagingQos: new MessagingQos(), subscriptionRequest: subscriptionRequest as any }); checkZ4Header(subscriptionRequestId); // broadcastSubscriptionRequest const broadcastSubscriptionRequestId = "testBroadcastSubscriptionRequestId"; const broadcastSubscriptionRequest = new BroadcastSubscriptionRequest({ subscribedToName: "broadcastEvent", subscriptionId: broadcastSubscriptionRequestId } as any); await dispatcher.sendBroadcastSubscriptionRequest({ from: proxyId, toDiscoveryEntry, messagingQos: new MessagingQos(), subscriptionRequest: broadcastSubscriptionRequest as any }); checkZ4Header(broadcastSubscriptionRequestId); // multicastSubscriptionRequest const multicastSubscriptionRequestId = "testMulticastSubscriptionRequestId"; const multicastSubscriptionRequest = new MulticastSubscriptionRequest({ subscribedToName: "multicastEvent", subscriptionId: multicastSubscriptionRequestId, multicastId: "multicastId" } as any); await dispatcher.sendBroadcastSubscriptionRequest({ from: proxyId, toDiscoveryEntry, messagingQos: new MessagingQos(), subscriptionRequest: multicastSubscriptionRequest }); expect(clusterControllerMessagingStub.transmit).toHaveBeenCalledTimes(0); // subscriptionStop const subscriptionStopId = "testSubscriptionStopId"; const subscriptionStop = new SubscriptionStop({ subscriptionId: subscriptionStopId } as any); await dispatcher.sendSubscriptionStop({ from: proxyId, toDiscoveryEntry, subscriptionStop: subscriptionStop as any, messagingQos: new MessagingQos() }); checkZ4Header(subscriptionStopId); // publication const expectedExpiryDate = Date.now() + 60000; const publicationId = "testPublicationId"; const publication = SubscriptionPublication.create({ subscriptionId: publicationId }); dispatcher.sendPublication( { from: proxyId, to: toDiscoveryEntry, expiryDate: expectedExpiryDate }, publication ); checkZ4Header(publicationId); }); });
the_stack
import { BoundingBox } from './Collision/BoundingBox'; import { Engine } from './Engine'; import { Vector, vec } from './Math/vector'; import { Logger } from './Util/Log'; import { SpriteSheet } from './Drawing/SpriteSheet'; import * as Events from './Events'; import { Configurable } from './Configurable'; import { Entity } from './EntityComponentSystem/Entity'; import { TransformComponent } from './EntityComponentSystem/Components/TransformComponent'; import { BodyComponent } from './Collision/BodyComponent'; import { CollisionType } from './Collision/CollisionType'; import { Shape } from './Collision/Colliders/Shape'; import { ExcaliburGraphicsContext, GraphicsComponent, hasGraphicsTick } from './Graphics'; import * as Graphics from './Graphics'; import { CanvasDrawComponent, Sprite } from './Drawing/Index'; import { Sprite as LegacySprite } from './Drawing/Index'; import { removeItemFromArray } from './Util/Util'; import { obsolete } from './Util/Decorators'; import { MotionComponent } from './EntityComponentSystem/Components/MotionComponent'; import { ColliderComponent } from './Collision/ColliderComponent'; import { CompositeCollider } from './Collision/Colliders/CompositeCollider'; /** * @hidden */ export class TileMapImpl extends Entity { private _token = 0; private _onScreenXStart: number = 0; private _onScreenXEnd: number = 9999; private _onScreenYStart: number = 0; private _onScreenYEnd: number = 9999; private _spriteSheets: { [key: string]: Graphics.SpriteSheet } = {}; private _legacySpriteMap = new Map<Graphics.Sprite, Sprite>(); public logger: Logger = Logger.getInstance(); public readonly data: Cell[] = []; private _rows: Cell[][] = []; private _cols: Cell[][] = []; public visible = true; public isOffscreen = false; public readonly cellWidth: number; public readonly cellHeight: number; public readonly rows: number; public readonly cols: number; private _dirty = true; public flagDirty() { this._dirty = true; } private _transform: TransformComponent; private _motion: MotionComponent; private _collider: ColliderComponent; private _composite: CompositeCollider; public get x(): number { return this._transform.pos.x ?? 0; } public set x(val: number) { if (this._transform?.pos) { this.get(TransformComponent).pos = vec(val, this.y); } } public get y(): number { return this._transform?.pos.y ?? 0; } public set y(val: number) { if (this._transform?.pos) { this._transform.pos = vec(this.x, val); } } public get z(): number { return this._transform.z ?? 0; } public set z(val: number) { if (this._transform?.z) { this._transform.z = val; } } public get rotation(): number { return this._transform?.rotation ?? 0; } public set rotation(val: number) { if (this._transform?.rotation) { this._transform.rotation = val; } } public get scale(): Vector { return this._transform?.scale ?? Vector.One; } public set scale(val: Vector) { if (this._transform?.scale) { this._transform.scale = val; } } public get pos(): Vector { return this._transform.pos; } public set pos(val: Vector) { this._transform.pos = val; } public get vel(): Vector { return this._motion.vel; } public set vel(val: Vector) { this._motion.vel = val; } public on(eventName: Events.preupdate, handler: (event: Events.PreUpdateEvent<TileMap>) => void): void; public on(eventName: Events.postupdate, handler: (event: Events.PostUpdateEvent<TileMap>) => void): void; public on(eventName: Events.predraw, handler: (event: Events.PreDrawEvent) => void): void; public on(eventName: Events.postdraw, handler: (event: Events.PostDrawEvent) => void): void; public on(eventName: string, handler: (event: Events.GameEvent<any>) => void): void; public on(eventName: string, handler: (event: any) => void): void { super.on(eventName, handler); } /** * @param xOrConfig The x coordinate to anchor the TileMap's upper left corner (should not be changed once set) or TileMap option bag * @param y The y coordinate to anchor the TileMap's upper left corner (should not be changed once set) * @param cellWidth The individual width of each cell (in pixels) (should not be changed once set) * @param cellHeight The individual height of each cell (in pixels) (should not be changed once set) * @param rows The number of rows in the TileMap (should not be changed once set) * @param cols The number of cols in the TileMap (should not be changed once set) */ constructor(xOrConfig: number | TileMapArgs, y: number, cellWidth: number, cellHeight: number, rows: number, cols: number) { super(); if (xOrConfig && typeof xOrConfig === 'object') { const config = xOrConfig; xOrConfig = config.x; y = config.y; cellWidth = config.cellWidth; cellHeight = config.cellHeight; rows = config.rows; cols = config.cols; } this.addComponent(new TransformComponent()); this.addComponent(new MotionComponent()); this.addComponent( new BodyComponent({ type: CollisionType.Fixed }) ); this.addComponent(new CanvasDrawComponent((ctx, delta) => this.draw(ctx, delta))); this.addComponent( new GraphicsComponent({ onPostDraw: (ctx, delta) => this.draw(ctx, delta) }) ); this.addComponent(new ColliderComponent()); this._transform = this.get(TransformComponent); this._motion = this.get(MotionComponent); this._collider = this.get(ColliderComponent); this._composite = this._collider.useCompositeCollider([]); this.x = <number>xOrConfig; this.y = y; this.cellWidth = cellWidth; this.cellHeight = cellHeight; this.rows = rows; this.cols = cols; this.data = new Array<Cell>(rows * cols); this._rows = new Array(rows); this._cols = new Array(cols); let currentCol: Cell[] = []; for (let i = 0; i < cols; i++) { for (let j = 0; j < rows; j++) { const cd = new Cell(i * cellWidth + <number>xOrConfig, j * cellHeight + y, cellWidth, cellHeight, i + j * cols); cd.map = this; this.data[i + j * cols] = cd; currentCol.push(cd); if (!this._rows[j]) { this._rows[j] = []; } this._rows[j].push(cd); } this._cols[i] = currentCol; currentCol = []; } this.get(GraphicsComponent).localBounds = new BoundingBox({ left: 0, top: 0, right: this.cols * this.cellWidth, bottom: this.rows * this.cellHeight }); } public _initialize(engine: Engine) { super._initialize(engine); } /** * * @param key * @param spriteSheet * @deprecated No longer used, will be removed in v0.26.0 */ public registerSpriteSheet(key: string, spriteSheet: SpriteSheet): void; public registerSpriteSheet(key: string, spriteSheet: Graphics.SpriteSheet): void; @obsolete({ message: 'No longer used, will be removed in v0.26.0' }) public registerSpriteSheet(key: string, spriteSheet: SpriteSheet | Graphics.SpriteSheet): void { if (spriteSheet instanceof Graphics.SpriteSheet) { this._spriteSheets[key] = spriteSheet; } else { this._spriteSheets[key] = Graphics.SpriteSheet.fromLegacySpriteSheet(spriteSheet); } } /** * Tiles colliders based on the solid tiles in the tilemap. */ private _updateColliders(): void { this._composite.clearColliders(); const colliders: BoundingBox[] = []; let current: BoundingBox; // Bad square tessalation algo for (let i = 0; i < this.cols; i++) { // Scan column for colliders for (let j = 0; j < this.rows; j++) { // Columns start with a new collider if (j === 0) { current = null; } const tile = this.data[i + j * this.cols]; // Current tile in column is solid build up current collider if (tile.solid) { if (!current) { current = tile.bounds; } else { current = current.combine(tile.bounds); } } else { // Not solid skip and cut off the current collider if (current) { colliders.push(current); } current = null; } } // After a column is complete check to see if it can be merged into the last one if (current) { // if previous is the same combine it const prev = colliders[colliders.length - 1]; if (prev && prev.top === current.top && prev.bottom === current.bottom) { colliders[colliders.length - 1] = prev.combine(current); } else { // else new collider colliders.push(current); } } } this._composite = this._collider.useCompositeCollider([]); for (const c of colliders) { const collider = Shape.Box(c.width, c.height, Vector.Zero, vec(c.left - this.pos.x, c.top - this.pos.y)); collider.owner = this; this._composite.addCollider(collider); } this._collider.update(); } /** * Returns the [[Cell]] by index (row major order) */ public getCellByIndex(index: number): Cell { return this.data[index]; } /** * Returns the [[Cell]] by its x and y coordinates */ public getCell(x: number, y: number): Cell { if (x < 0 || y < 0 || x >= this.cols || y >= this.rows) { return null; } return this.data[x + y * this.cols]; } /** * Returns the [[Cell]] by testing a point in global coordinates, * returns `null` if no cell was found. */ public getCellByPoint(x: number, y: number): Cell { x = Math.floor((x - this.pos.x) / this.cellWidth); y = Math.floor((y - this.pos.y) / this.cellHeight); const cell = this.getCell(x, y); if (x >= 0 && y >= 0 && x < this.cols && y < this.rows && cell) { return cell; } return null; } public getRows(): readonly Cell[][] { return this._rows; } public getColumns(): readonly Cell[][] { return this._cols; } public onPreUpdate(_engine: Engine, _delta: number) { // Override me } public onPostUpdate(_engine: Engine, _delta: number) { // Override me } public update(engine: Engine, delta: number) { this.onPreUpdate(engine, delta); this.emit('preupdate', new Events.PreUpdateEvent(engine, delta, this)); if (this._dirty) { this._dirty = false; this._updateColliders(); } this._token++; const worldBounds = engine.getWorldBounds(); const worldCoordsUpperLeft = vec(worldBounds.left, worldBounds.top); const worldCoordsLowerRight = vec(worldBounds.right, worldBounds.bottom); this._onScreenXStart = Math.max(Math.floor((worldCoordsUpperLeft.x - this.x) / this.cellWidth) - 2, 0); this._onScreenYStart = Math.max(Math.floor((worldCoordsUpperLeft.y - this.y) / this.cellHeight) - 2, 0); this._onScreenXEnd = Math.max(Math.floor((worldCoordsLowerRight.x - this.x) / this.cellWidth) + 2, 0); this._onScreenYEnd = Math.max(Math.floor((worldCoordsLowerRight.y - this.y) / this.cellHeight) + 2, 0); this._transform.pos = vec(this.x, this.y); this.onPostUpdate(engine, delta); this.emit('postupdate', new Events.PostUpdateEvent(engine, delta, this)); } /** * Draws the tile map to the screen. Called by the [[Scene]]. * @param ctx CanvasRenderingContext2D or ExcaliburGraphicsContext * @param delta The number of milliseconds since the last draw */ public draw(ctx: CanvasRenderingContext2D | ExcaliburGraphicsContext, delta: number): void { this.emit('predraw', new Events.PreDrawEvent(ctx as any, delta, this)); // TODO fix event let x = this._onScreenXStart; const xEnd = Math.min(this._onScreenXEnd, this.cols); let y = this._onScreenYStart; const yEnd = Math.min(this._onScreenYEnd, this.rows); let graphics: Graphics.Graphic[], graphicsIndex: number, graphicsLen: number; for (x; x < xEnd; x++) { for (y; y < yEnd; y++) { // get non-negative tile sprites graphics = this.getCell(x, y).graphics; for (graphicsIndex = 0, graphicsLen = graphics.length; graphicsIndex < graphicsLen; graphicsIndex++) { // draw sprite, warning if sprite doesn't exist const graphic = graphics[graphicsIndex]; if (graphic) { if (!(ctx instanceof CanvasRenderingContext2D)) { if (hasGraphicsTick(graphic)) { graphic?.tick(delta, this._token); } graphic.draw(ctx, x * this.cellWidth, y * this.cellHeight); } else if (graphic instanceof Graphics.Sprite) { // TODO legacy drawing mode if (!this._legacySpriteMap.has(graphic)) { this._legacySpriteMap.set(graphic, Graphics.Sprite.toLegacySprite(graphic)); } this._legacySpriteMap.get(graphic).draw(ctx, x * this.cellWidth, y * this.cellHeight); } } } } y = this._onScreenYStart; } this.emit('postdraw', new Events.PostDrawEvent(ctx as any, delta, this)); } } export interface TileMapArgs extends Partial<TileMapImpl> { x: number; y: number; cellWidth: number; cellHeight: number; rows: number; cols: number; } /** * The [[TileMap]] class provides a lightweight way to do large complex scenes with collision * without the overhead of actors. */ export class TileMap extends Configurable(TileMapImpl) { constructor(config: TileMapArgs); constructor(x: number, y: number, cellWidth: number, cellHeight: number, rows: number, cols: number); constructor(xOrConfig: number | TileMapArgs, y?: number, cellWidth?: number, cellHeight?: number, rows?: number, cols?: number) { super(xOrConfig, y, cellWidth, cellHeight, rows, cols); } } /** * @hidden */ export class CellImpl extends Entity { private _bounds: BoundingBox; /** * World space x coordinate of the left of the cell */ public readonly x: number; /** * World space y coordinate of the top of the cell */ public readonly y: number; /** * Width of the cell in pixels */ public readonly width: number; /** * Height of the cell in pixels */ public readonly height: number; /** * Current index in the tilemap */ public readonly index: number; /** * Reference to the TileMap this Cell is associated with */ public map: TileMap; private _solid = false; /** * Wether this cell should be treated as solid by the tilemap */ public get solid(): boolean { return this._solid; } /** * Wether this cell should be treated as solid by the tilemap */ public set solid(val: boolean) { this.map?.flagDirty(); this._solid = val; } /** * Current list of graphics for this cell */ public readonly graphics: Graphics.Graphic[] = []; /** * Abitrary data storage per cell, useful for any game specific data */ public data = new Map<string, any>(); /** * @param xOrConfig Gets or sets x coordinate of the cell in world coordinates or cell option bag * @param y Gets or sets y coordinate of the cell in world coordinates * @param width Gets or sets the width of the cell * @param height Gets or sets the height of the cell * @param index The index of the cell in row major order * @param solid Gets or sets whether this cell is solid * @param graphics The list of tile graphics to use to draw in this cell (in order) */ constructor( xOrConfig: number | CellArgs, y: number, width: number, height: number, index: number, solid: boolean = false, graphics: Graphics.Graphic[] = [] ) { super(); if (xOrConfig && typeof xOrConfig === 'object') { const config = xOrConfig; xOrConfig = config.x; y = config.y; width = config.width; height = config.height; index = config.index; solid = config.solid; graphics = config.sprites; } this.x = <number>xOrConfig; this.y = y; this.width = width; this.height = height; this.index = index; this.solid = solid; this.graphics = graphics; this._bounds = new BoundingBox(this.x, this.y, this.x + this.width, this.y + this.height); } public get bounds() { return this._bounds; } public get center(): Vector { return new Vector(this.x + this.width / 2, this.y + this.height / 2); } /** * Add another [[Sprite]] to this cell * @deprecated Use addSprite, will be removed in v0.26.0 */ @obsolete({ message: 'Will be removed in v0.26.0', alternateMethod: 'addSprite' }) public pushSprite(sprite: Graphics.Sprite | LegacySprite) { this.addGraphic(sprite); } /** * Add another [[Graphic]] to this TileMap cell * @param graphic */ public addGraphic(graphic: Graphics.Graphic | LegacySprite) { if (graphic instanceof LegacySprite) { this.graphics.push(Graphics.Sprite.fromLegacySprite(graphic)); } else { this.graphics.push(graphic); } } /** * Remove an instance of a [[Graphic]] from this cell */ public removeGraphic(graphic: Graphics.Graphic | LegacySprite) { removeItemFromArray(graphic, this.graphics); } /** * Clear all graphis from this cell */ public clearGraphics() { this.graphics.length = 0; } } export interface CellArgs extends Partial<CellImpl> { x: number; y: number; width: number; height: number; index: number; solid?: boolean; sprites?: Graphics.Sprite[]; } /** * TileMap Cell * * A light-weight object that occupies a space in a collision map. Generally * created by a [[TileMap]]. * * Cells can draw multiple sprites. Note that the order of drawing is the order * of the sprites in the array so the last one will be drawn on top. You can * use transparency to create layers this way. */ export class Cell extends Configurable(CellImpl) { constructor(config: CellArgs); constructor(x: number, y: number, width: number, height: number, index: number, solid?: boolean, sprites?: Graphics.Sprite[]); constructor( xOrConfig: number | CellArgs, y?: number, width?: number, height?: number, index?: number, solid?: boolean, sprites?: Graphics.Sprite[] ) { super(xOrConfig, y, width, height, index, solid, sprites); } }
the_stack
import { getContrastingStroke, getAccessibleStrokes } from './colors'; import { createUrl } from './accessibilityUtils'; import { getBrowser } from './browser-util'; import { transitionEndAll } from './transitionEndAll'; import { select } from 'd3-selection'; const isSafari = getBrowser() === 'Safari'; const indices = { categorical: [[0], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5]], sequential: [ [0], [0], [0, 8], [0, 4, 8], [1, 3, 5, 7], [0, 2, 4, 6, 8], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8] ], diverging_center: [ , // this scheme is odd-length only [5], // this index does not appear on this scheme , [0, 5, 10], // this index does not appear on this scheme , [1, 3, 5, 7, 9], // this index does not appear on this scheme , [2, 3, 4, 5, 6, 7, 8], // this index does not appear on this scheme , [1, 2, 3, 4, 5, 6, 7, 8, 9], // this index does not appear on this scheme , [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ], diverging_split: [ , , // this scheme is even-length only // this index does not appear on this scheme [1, 8], // this index does not appear on this scheme , [0, 3, 6, 9], // this index does not appear on this scheme , [0, 2, 4, 5, 7, 9], // this index does not appear on this scheme , [0, 1, 2, 3, 6, 7, 8, 9], // this index does not appear on this scheme , [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ] }; export function getTexture({ scheme, id, index, fillColor, textureColor }: { scheme: string; id: string; index: number; fillColor: string; textureColor: string; }) { const textureData = { categorical: [ { attributes: { width: 12, height: 12, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12', height: '12', fill: `${fillColor}` } }, { name: 'path', attributes: { d: 'M 0,0 l 12,12 M -3,9 l 6,6 M 9,-3 l 6,6', 'stroke-width': '1', 'shape-rendering': 'auto', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12, height: 12, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12', height: '12', fill: `${fillColor}` } }, { name: 'circle', attributes: { cx: '6', cy: '6', r: '1', fill: `${textureColor}`, stroke: '#343434', 'stroke-width': '0' } }, { name: 'circle', attributes: { cx: '0', cy: '0', r: '1', fill: `${textureColor}`, stroke: '#343434', 'stroke-width': '0' } }, { name: 'circle', attributes: { cx: '0', cy: '12', r: '1', fill: `${textureColor}`, stroke: '#343434', 'stroke-width': '0' } }, { name: 'circle', attributes: { cx: '12', cy: '0', r: '1', fill: `${textureColor}`, stroke: '#343434', 'stroke-width': '0' } }, { name: 'circle', attributes: { cx: '12', cy: '12', r: '1', fill: `${textureColor}`, stroke: '#343434', 'stroke-width': '0' } } ] }, { attributes: { width: 24, height: 24, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '24', height: '24', fill: `${fillColor}` } }, { name: 'path', attributes: { d: 'M 0,0 l 24,24 M -6,18 l 12,12 M 18,-6 l 12,12', 'stroke-width': '1', 'shape-rendering': 'auto', stroke: `${textureColor}`, 'stroke-linecap': 'square' } }, { name: 'path', attributes: { d: 'M 0,24 l 24,-24 M -6,6 l 12,-12 M 18,30 l 12,-12', 'stroke-width': '1', 'shape-rendering': 'auto', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12, height: 12, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12', height: '12', fill: `${fillColor}` } }, { name: 'path', attributes: { d: 'M 4.5,4.5l3,3M4.5,7.5l3,-3', fill: 'transparent', stroke: `${textureColor}`, 'stroke-width': '1', 'stroke-linecap': 'square', 'shape-rendering': 'auto' } } ] }, { attributes: { width: 10, height: 10, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10', height: '10', fill: `${fillColor}` } }, { name: 'path', attributes: { d: 'M 5, 0 l 0, 10', 'stroke-width': '1', 'shape-rendering': 'auto', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12, height: 12, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12', height: '12', fill: `${fillColor}` } }, { name: 'circle', attributes: { cx: '6', cy: '6', r: '1.5', fill: 'none', stroke: `${textureColor}`, 'stroke-width': '1' } }, { name: 'circle', attributes: { cx: '2', cy: '10', r: '1.5', fill: 'none', stroke: `${textureColor}`, 'stroke-width': '1' } }, { name: 'circle', attributes: { cx: '10', cy: '2', r: '1.5', fill: 'none', stroke: `${textureColor}`, 'stroke-width': '1' } } ] } ], sequential: [ { attributes: { width: 10, height: 10, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10', height: '10', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 0 L 10 0M 0 10 L 10 10', 'stroke-width': '1', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 52.40843064167849, height: 10.187166949552141, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '52.40843064167849', height: '10.187166949552141', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -52.40843064167849 10.187166949552141 L 52.40843064167849 -10.187166949552141M -52.40843064167849 20.374333899104283 L 104.81686128335699 -10.187166949552141M 0 20.374333899104283 L 104.81686128335699 0', 'stroke-width': '2', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 26.694671625540145, height: 10.785347426775834, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '26.694671625540145', height: '10.785347426775834', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -26.694671625540145 10.785347426775834 L 26.694671625540145 -10.785347426775834M -26.694671625540145 21.570694853551668 L 53.38934325108029 -10.785347426775834M 0 21.570694853551668 L 53.38934325108029 0', 'stroke-width': '3', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 17.882916499714003, height: 12.062179485039053, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '17.882916499714003', height: '12.062179485039053', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -17.882916499714003 12.062179485039053 L 17.882916499714003 -12.062179485039053M -17.882916499714003 24.124358970078106 L 35.76583299942801 -12.062179485039053M 0 24.124358970078106 L 35.76583299942801 0', 'stroke-width': '4', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 14.142135623730951, height: 14.14213562373095, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '14.142135623730951', height: '14.14213562373095', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -14.142135623730951 14.14213562373095 L 14.142135623730951 -14.14213562373095M -14.142135623730951 28.2842712474619 L 28.284271247461902 -14.14213562373095M 0 28.2842712474619 L 28.284271247461902 0', 'stroke-width': '5', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12.062179485039053, height: 17.882916499714003, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12.062179485039053', height: '17.882916499714003', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -12.062179485039053 17.882916499714003 L 12.062179485039053 -17.882916499714003M -12.062179485039053 35.76583299942801 L 24.124358970078106 -17.882916499714003M 0 35.76583299942801 L 24.124358970078106 0', 'stroke-width': '6', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 10.863603774052963, height: 25.593046652474495, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10.863603774052963', height: '25.593046652474495', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -10.863603774052963 25.593046652474495 L 10.863603774052963 -25.593046652474495M -10.863603774052963 51.18609330494899 L 21.727207548105927 -25.593046652474495M 0 51.18609330494899 L 21.727207548105927 0', 'stroke-width': '7', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 10.187166949552141, height: 52.40843064167844, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10.187166949552141', height: '52.40843064167844', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -10.187166949552141 52.40843064167844 L 10.187166949552141 -52.40843064167844M -10.187166949552141 104.81686128335689 L 20.374333899104283 -52.40843064167844M 0 104.81686128335689 L 20.374333899104283 0', 'stroke-width': '8', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 10, height: 10, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10', height: '10', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 0 L 0 10M 10 0 L 10 10', 'stroke-width': '9', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] } ], diverging_split: [ { attributes: { width: 10.35276180410083, height: 38.63703305156273, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10.35276180410083', height: '38.63703305156273', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -38.63703305156273 L 20.70552360820166 38.63703305156273M -10.35276180410083 -38.63703305156273 L 10.35276180410083 38.63703305156273M -10.35276180410083 0 L 10.35276180410083 77.27406610312546', 'stroke-width': '9', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 11.547005383792516, height: 20.000000000000004, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '11.547005383792516', height: '20.000000000000004', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -20.000000000000004 L 23.094010767585033 20.000000000000004M -11.547005383792516 -20.000000000000004 L 11.547005383792516 20.000000000000004M -11.547005383792516 0 L 11.547005383792516 40.00000000000001', 'stroke-width': '7', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 14.142135623730951, height: 14.142135623730951, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '14.142135623730951', height: '14.142135623730951', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -14.142135623730951 L 28.284271247461902 14.142135623730951M -14.142135623730951 -14.142135623730951 L 14.142135623730951 14.142135623730951M -14.142135623730951 0 L 14.142135623730951 28.284271247461902', 'stroke-width': '5', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 20.000000000000004, height: 11.547005383792516, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '20.000000000000004', height: '11.547005383792516', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -11.547005383792516 L 40.00000000000001 11.547005383792516M -20.000000000000004 -11.547005383792516 L 20.000000000000004 11.547005383792516M -20.000000000000004 0 L 20.000000000000004 23.094010767585033', 'stroke-width': '3', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 38.63703305156273, height: 10.35276180410083, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '38.63703305156273', height: '10.35276180410083', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -10.35276180410083 L 77.27406610312546 10.35276180410083M -38.63703305156273 -10.35276180410083 L 38.63703305156273 10.35276180410083M -38.63703305156273 0 L 38.63703305156273 20.70552360820166', 'stroke-width': '1', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 38.63703305156273, height: 10.35276180410083, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '38.63703305156273', height: '10.35276180410083', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -38.63703305156273 10.35276180410083 L 38.63703305156273 -10.35276180410083M -38.63703305156273 20.70552360820166 L 77.27406610312546 -10.35276180410083M 0 20.70552360820166 L 77.27406610312546 0', 'stroke-width': '1', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 20.000000000000004, height: 11.547005383792515, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '20.000000000000004', height: '11.547005383792515', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -20.000000000000004 11.547005383792515 L 20.000000000000004 -11.547005383792515M -20.000000000000004 23.09401076758503 L 40.00000000000001 -11.547005383792515M 0 23.09401076758503 L 40.00000000000001 0', 'stroke-width': '3', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 14.142135623730951, height: 14.14213562373095, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '14.142135623730951', height: '14.14213562373095', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -14.142135623730951 14.14213562373095 L 14.142135623730951 -14.14213562373095M -14.142135623730951 28.2842712474619 L 28.284271247461902 -14.14213562373095M 0 28.2842712474619 L 28.284271247461902 0', 'stroke-width': '5', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 11.547005383792516, height: 20.000000000000004, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '11.547005383792516', height: '20.000000000000004', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -11.547005383792516 20.000000000000004 L 11.547005383792516 -20.000000000000004M -11.547005383792516 40.00000000000001 L 23.094010767585033 -20.000000000000004M 0 40.00000000000001 L 23.094010767585033 0', 'stroke-width': '7', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 10.35276180410083, height: 38.637033051562696, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '10.35276180410083', height: '38.637033051562696', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -10.35276180410083 38.637033051562696 L 10.35276180410083 -38.637033051562696M -10.35276180410083 77.27406610312539 L 20.70552360820166 -38.637033051562696M 0 77.27406610312539 L 20.70552360820166 0', 'stroke-width': '9', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] } ], diverging_center: [ { attributes: { width: 12.423314164920995, height: 46.36443966187528, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12.423314164920995', height: '46.36443966187528', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -46.36443966187528 L 24.84662832984199 46.36443966187528M -12.423314164920995 -46.36443966187528 L 12.423314164920995 46.36443966187528M -12.423314164920995 0 L 12.423314164920995 92.72887932375056', 'stroke-width': '11', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 13.85640646055102, height: 24.000000000000004, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '13.85640646055102', height: '24.000000000000004', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -24.000000000000004 L 27.71281292110204 24.000000000000004M -13.85640646055102 -24.000000000000004 L 13.85640646055102 24.000000000000004M -13.85640646055102 0 L 13.85640646055102 48.00000000000001', 'stroke-width': '9', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 16.970562748477143, height: 16.970562748477143, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '16.970562748477143', height: '16.970562748477143', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -16.970562748477143 L 33.941125496954285 16.970562748477143M -16.970562748477143 -16.970562748477143 L 16.970562748477143 16.970562748477143M -16.970562748477143 0 L 16.970562748477143 33.941125496954285', 'stroke-width': '7', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 24.000000000000004, height: 13.85640646055102, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '24.000000000000004', height: '13.85640646055102', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -13.85640646055102 L 48.00000000000001 13.85640646055102M -24.000000000000004 -13.85640646055102 L 24.000000000000004 13.85640646055102M -24.000000000000004 0 L 24.000000000000004 27.71281292110204', 'stroke-width': '5', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 46.36443966187528, height: 12.423314164920995, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '46.36443966187528', height: '12.423314164920995', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 -12.423314164920995 L 92.72887932375056 12.423314164920995M -46.36443966187528 -12.423314164920995 L 46.36443966187528 12.423314164920995M -46.36443966187528 0 L 46.36443966187528 24.84662832984199', 'stroke-width': '3', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12, height: 12, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12', height: '12', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M 0 0 L 12 0M 0 12 L 12 12', 'stroke-width': '1', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 46.36443966187528, height: 12.423314164920995, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '46.36443966187528', height: '12.423314164920995', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -46.36443966187528 12.423314164920995 L 46.36443966187528 -12.423314164920995M -46.36443966187528 24.84662832984199 L 92.72887932375056 -12.423314164920995M 0 24.84662832984199 L 92.72887932375056 0', 'stroke-width': '3', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 24.000000000000004, height: 13.856406460551018, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '24.000000000000004', height: '13.856406460551018', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -24.000000000000004 13.856406460551018 L 24.000000000000004 -13.856406460551018M -24.000000000000004 27.712812921102035 L 48.00000000000001 -13.856406460551018M 0 27.712812921102035 L 48.00000000000001 0', 'stroke-width': '5', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 16.970562748477143, height: 16.97056274847714, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '16.970562748477143', height: '16.97056274847714', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -16.970562748477143 16.97056274847714 L 16.970562748477143 -16.97056274847714M -16.970562748477143 33.94112549695428 L 33.941125496954285 -16.97056274847714M 0 33.94112549695428 L 33.941125496954285 0', 'stroke-width': '7', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 13.85640646055102, height: 24.000000000000004, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '13.85640646055102', height: '24.000000000000004', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -13.85640646055102 24.000000000000004 L 13.85640646055102 -24.000000000000004M -13.85640646055102 48.00000000000001 L 27.71281292110204 -24.000000000000004M 0 48.00000000000001 L 27.71281292110204 0', 'stroke-width': '9', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] }, { attributes: { width: 12.423314164920995, height: 46.36443966187523, patternUnits: 'userSpaceOnUse', id: `${id}`, class: 'VCL-texture-pattern' }, children: [ { name: 'rect', attributes: { width: '12.423314164920995', height: '46.36443966187523', fill: `${fillColor}`, stroke: 'rgba(255, 0, 0, 0.1)', 'stroke-width': '0' } }, { name: 'path', attributes: { d: 'M -12.423314164920995 46.36443966187523 L 12.423314164920995 -46.36443966187523M -12.423314164920995 92.72887932375046 L 24.84662832984199 -46.36443966187523M 0 92.72887932375046 L 24.84662832984199 0', 'stroke-width': '11', stroke: `${textureColor}`, 'stroke-linecap': 'square' } } ] } ] }; // need to check categorical index to fill constancy!! Should import the scheme here return textureData[scheme][index]; } export const checkAttributeTransitions = (source, attributeArray) => { let change = false; let i = 0; while (!change && i < attributeArray.length) { const d = attributeArray[i]; const currentAttributeValue = d.numeric ? parseFloat(source.attr(d.attr)) : source.attr(d.attr); change = !(currentAttributeValue === d.newValue); i++; } return change; }; function runTextureLifecycle(source, data, transitionDisabled?) { const parent = select(source); let defs = parent.select('defs'); if (!defs.size()) { defs = parent.append('defs'); } const patterns = defs.selectAll('.VCL-texture-pattern').data(data, d => d.scheme + d.index); // append new patterns const enter = patterns.enter().append('pattern'); // update all existing patterns const update = patterns.merge(enter); update .transition('exit') .duration(!transitionDisabled ? 750 : 0) .call(transitionEndAll, () => { // removing here instead of earlier compensates for failing a race condition // caused by Stencil where multiple lifecycles are trying to exit patterns.exit().remove(); }); update .each((d, i, n) => { const patternAttributes = Object.keys(d.attributes); const me = select(n[i]); patternAttributes.forEach(attr => { me.attr(attr, d.attributes[attr]); }); }) .attr('patternContentUnits', 'userSpaceOnUse') .attr('x', 0) .attr('y', 0); const children = update.selectAll('.VCL-t-p-e').data(d => d.children, (d, i) => d.name + i); // remove children that are a different type, by slot order children.exit().remove(); // append new children, also according to slot order and type const enterChildren = children .enter() .append(d => { return document.createElementNS('http://www.w3.org/2000/svg', d.name); }) .attr('class', 'VCL-t-p-e'); // update all existing children const updateChildren = children.merge(enterChildren); updateChildren.each((d, i, n) => { const me = select(n[i]); const childAttributes = Object.keys(d.attributes); childAttributes.forEach(attr => { me.attr(attr, d.attributes[attr]); }); }); } export function convertColorsToTextures({ colors, rootSVG, id, scheme, disableTransitions }: { colors: any; rootSVG: any; id: string; scheme?: string; disableTransitions?: boolean; }) { const output = []; const textures = []; let i = 0; const colorArray = colors.range ? colors.range() : colors; // if (colorArray.length === 1) { // output.push; // } // removePatterns(rootSVG); colorArray.forEach(color => { // we create a unique ID for each texture let textureId = id + '_texture_' + i; // get one color for the texture/stroke and one for the fill, depending on the scheme const contrastedColors = prepareStrokeColorsFromScheme(color, i, colorArray, scheme); // we retrieve the appropriate pattern data for the texture const texture = getTexture({ scheme: contrastedColors.textureScheme, id: textureId, index: indices[contrastedColors.textureScheme][colors.length][i], fillColor: contrastedColors.fillColor, textureColor: contrastedColors.textureColor }); // we append the pattern to the dom // appendPattern(rootSVG, texture); texture.scheme = contrastedColors.textureScheme; texture.index = indices[contrastedColors.textureScheme][colors.length][i]; textures.push(texture); // we add the url to this pattern to our output array output.push(createUrl(textureId)); i++; }); runTextureLifecycle(rootSVG, textures, disableTransitions); // return array of "url(#[id])" strings for use in place of hex codes for element fills return output; } export const prepareStrokeColorsFromScheme = (color, i, colorArray, scheme?) => { // the sequential scheme colors are easiest, so they are default let fillColor = colorArray[0]; let textureColor = colorArray[colorArray.length - 1]; const textureScheme = scheme === 'categorical' || !scheme ? 'categorical' : scheme === 'sequential' ? 'sequential' : colorArray.length % 2 ? 'diverging_center' // odd numbered scheme : 'diverging_split'; // even numbered scheme if (textureScheme === 'categorical') { // we calculate the appropriate stroke color for the texture textureColor = getContrastingStroke(color); fillColor = color; } else if (textureScheme !== 'sequential') { if (textureScheme.includes('center')) { // center diverging scheme const firstHalfIndex = (colorArray.length - 1) / 2 - 1; const middleIndex = firstHalfIndex + 1; const secondHalfIndex = middleIndex + 1; if (i <= firstHalfIndex) { textureColor = colorArray[0]; fillColor = colorArray[firstHalfIndex]; } else if (i >= secondHalfIndex) { textureColor = colorArray[colorArray.length - 1]; fillColor = colorArray[secondHalfIndex]; } else { // we calculate the appropriate stroke color for the texture textureColor = getContrastingStroke(color); fillColor = color; } } else { // split diverging scheme const topHalfIndex = colorArray.length / 2; if (i < topHalfIndex) { textureColor = colorArray[0]; fillColor = colorArray[topHalfIndex - 1]; } else { textureColor = colorArray[colorArray.length - 1]; fillColor = colorArray[topHalfIndex]; } } } return { fillColor, textureColor, textureScheme }; }; export const removeFilters = root => { select(root) .selectAll('.VCL-accessibility-stroke-filter') .remove(); }; export const createTextStrokeFilter = ({ root, id, color, strokeSizeOverride }: { root: any; id: string; color: string; strokeSizeOverride?: number; }) => { const sanitizedColor = color[0] === '#' ? color.substr(1) : color; const s = ((strokeSizeOverride || '') + '').replace('.', 'p'); const strokeClass = 'VCL-t-s-f-' + sanitizedColor + s; const strokeId = strokeClass + id + s; let filter = select(root).select('.' + strokeClass); if (!filter.size()) { // select(root).selectAll('VCL-text-stroke-filter').remove() let defs = select(root).select('defs'); if (!defs.size()) { defs = select(root).append('defs'); } filter = defs .append('filter') .attr('id', strokeId) .attr('class', strokeClass); filter .append('feMorphology') .attr('in', 'SourceAlpha') .attr('result', 'dilatedText') .attr('operator', 'dilate') .attr('radius', strokeSizeOverride || 1.5); filter .append('feFlood') .attr('flood-color', color || '#ffffff') .attr('flood-opacity', 1) .attr('result', 'whiteTextFlood'); filter .append('feComposite') .attr('in', 'whiteTextFlood') .attr('in2', 'dilatedText') .attr('operator', 'in') .attr('result', 'textOutline'); const merge = filter.append('feMerge'); merge.append('feMergeNode').attr('in', 'textOutline'); if (!strokeSizeOverride) { // this ensures that text (which use the default) will always have effective outlines merge.append('feMergeNode').attr('in', 'textOutline'); merge.append('feMergeNode').attr('in', 'textOutline'); } merge.append('feMergeNode').attr('in', 'SourceGraphic'); } else { filter.attr('id', strokeId); } return createUrl(strokeId); }; export const createMultiStrokeFilter = ({ root, id, state, fillColor, strokeWidth, forceStrokeColor, includeOuterStroke, strokeOnHover, alwaysShowStroke, stacked }: { root: any; id: string; state: string; fillColor: string; strokeWidth: number; forceStrokeColor?: string; includeOuterStroke?: boolean; strokeOnHover?: boolean; alwaysShowStroke?: boolean; stacked?: boolean; }) => { const rootDefs = select(root).select('defs'); const strokes = getAccessibleStrokes(fillColor); // dark fills that are at rest don't need a stroke const primaryStroke = (state !== 'hover' || strokeOnHover) && (strokes.length === 1 || state === 'click') ? strokes[0] : fillColor; // cleanup is always the same as base fill const cleanupStroke = fillColor; // if there is an edge, use it - this is only for dark fills const edgeStroke = strokes[1] || ''; // if we include outer stroke, it is always white const outerStroke = includeOuterStroke ? '#ffffff' : ''; const filterId = 'VCL-filter-' + (primaryStroke[0] === '#' ? primaryStroke.substring(1) : primaryStroke) + '-' + state + '-' + id; if (rootDefs.select('#' + filterId).size()) { rootDefs.select('#' + filterId).remove(); } const filter = rootDefs .append('filter') .attr('id', filterId) .attr('class', 'VCL-accessibility-stroke-filter'); const data = createFilterData( state !== 'hover' && forceStrokeColor ? forceStrokeColor : primaryStroke, cleanupStroke, primaryStroke !== fillColor || state === 'hover' || alwaysShowStroke ? strokeWidth : 0, outerStroke, edgeStroke, !stacked ? 0 : 0.5 ); data.forEach(filterComposite => { filter .append('feMorphology') .attr('in', 'SourceAlpha') .attr('operator', filterComposite.operator) .attr('radius', filterComposite.radius) .attr( 'result', filterComposite.result ? filterComposite.result + '-morph' : 'morph-' + filterComposite.operator + '-' + filterComposite.radius ); if (filterComposite.color) { filter .append('feFlood') .attr('flood-color', filterComposite.color) .attr('result', filterComposite.result + '-color'); } filter .append('feComposite') .attr('in', filterComposite.result ? filterComposite.result + '-color' : 'SourceGraphic') .attr( 'in2', filterComposite.result ? filterComposite.result + '-morph' : 'morph-' + filterComposite.operator + '-' + filterComposite.radius ) .attr('operator', 'in') .attr('result', filterComposite.result ? filterComposite.result + '-stroke' : 'fill'); }); const feMerge = filter.append('feMerge'); data.forEach(filterComposite => { feMerge.append('feMergeNode').attr('in', filterComposite.result ? filterComposite.result + '-stroke' : 'fill'); }); return createUrl(filterId); }; const createFilterData = (primary, clean, strokeWidth, outside?, edge?, adjustForStack?) => { const output = []; const browser = getBrowser(); const mod = browser !== 'IE' && browser !== 'Edge' ? 0 : 1; let strokeStart = browser !== 'Safari' ? mod : 0.1; if (outside) { output.push({ color: outside, result: 'outside', operator: !adjustForStack ? 'dilate' : 'erode', radius: !adjustForStack ? 1 : 0 }); } if (edge) { strokeStart++; output.push({ color: edge, result: 'edge', operator: 'erode', radius: mod + adjustForStack }); } output.push({ color: primary, result: 'primary', operator: 'erode', radius: strokeStart + adjustForStack }); output.push({ color: clean, result: 'clean', operator: 'erode', radius: strokeStart + strokeWidth + adjustForStack }); output.push({ operator: 'erode', radius: strokeStart + strokeWidth + 1 + adjustForStack }); return output; }; export const removeHoverStrokes = (root: any) => { const className = 'vcl-accessibility-focus'; select(root) .selectAll('.' + className + '-hoverSource') .classed(className + '-hoverSource', false); select(root) .selectAll('.' + className + '-hover') .remove(); }; const removeDuplicateStrokes = (parent: any, id: string) => { const root = select(parent.ownerSVGElement); root.selectAll('.vcl-accessibility-focus-hoverSource').classed('vcl-accessibility-focus-hoverSource', false); root.select('#VCL-clip-' + id).remove(); root.select('#VCL-hover-stroke-' + id).remove(); root.select('#VCL-buffer-stroke' + id).remove(); root.select('#VCL-parent-' + id).remove(); }; export const drawHoverStrokes = ({ inputElement, id, key, strokeWidth, fill, recursive, strokeOverride }: { inputElement: any; id: string; key: any; strokeWidth: number; fill: string; recursive?: boolean; strokeOverride?: string; }) => { const strokes = getAccessibleStrokes(fill); const stroke = strokeOverride || strokes[0]; const shouldBuffer = !!strokes[1]; const uniqueElementId = createId(id, key); const source = inputElement.tagName !== 'DIV' ? inputElement : select(inputElement.parentNode) .select('svg') .node(); const className = 'vcl-accessibility-focus'; const shouldHideOutline = select(source) .style('outline') .includes('auto'); if (shouldHideOutline) { select(source) .style('outline-width', '0px') .style('outline-offset', '0px') .style('outline-color', 'none'); } const parent = source.parentNode; removeDuplicateStrokes(parent, uniqueElementId); select(source).classed(className + '-hoverSource', true); const dashedStrokeLayer = source.cloneNode(false); const darkElementBuffer = shouldBuffer ? source.cloneNode(false) : null; const clipPathElement = source.cloneNode(false); const clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'); clipPath.appendChild(clipPathElement); if (!recursive) { const parentOfParent = parent.parentNode; const parentCopy = parent.cloneNode(false); const newParent = select(parentCopy).attr('id', 'VCL-parent-' + uniqueElementId); parentCopy.appendChild(clipPath); parentCopy.appendChild(dashedStrokeLayer); if (shouldBuffer) { parentCopy.appendChild(darkElementBuffer); } if (parent.nextSibling) { parentOfParent.insertBefore(parentCopy, parent.nextSibling); } else { parentOfParent.appendChild(parentCopy); } applyDefaults(newParent, className); } else { if (source.nextSibling) { if (shouldBuffer) { parent.insertBefore(darkElementBuffer, source.nextSibling); } parent.insertBefore(dashedStrokeLayer, source.nextSibling); parent.insertBefore(clipPath, source.nextSibling); } else { parent.appendChild(clipPath); parent.appendChild(dashedStrokeLayer); if (shouldBuffer) { parent.appendChild(darkElementBuffer); } } } const clipId = 'VCL-clip-' + uniqueElementId; const url = createUrl(clipId); select(clipPath) .attr('id', clipId) .attr('clipPathUnits', 'userSpaceOnUse') .attr('class', className + '-highlight ' + className + '-hover'); const clip = select(clipPathElement) .attr('id', 'VCL-clip-element-' + uniqueElementId) .style('opacity', 1) .attr('opacity', 1); applyDefaults(clip, className); const strokeElement = select(dashedStrokeLayer) .attr('id', 'VCL-buffer-stroke-' + uniqueElementId) .style('opacity', 1) .attr('opacity', 1) .style('stroke', stroke); applyDefaults(strokeElement, className); applyOutlineOverride(strokeElement, strokeWidth, url, shouldBuffer, true); if (shouldBuffer) { const buffer = select(darkElementBuffer) .attr('id', 'VCL-buffer-stroke-' + uniqueElementId) .style('opacity', 1) .attr('opacity', 1) .style('stroke', fill); applyDefaults(buffer, className); applyOutlineOverride(buffer, 1, url, false, false); } }; // this is currently unused, but will allow for future strokes to transition with a chart // (rather than hiding during transition). See commented section in bar chart for use. export const mirrorStrokeTransition = ({ id, key, attribute, newValue, easing, duration }: { id: string; key: any; attribute: string; newValue: any; easing: any; duration: number; }) => { const baseId = createId(id, key); const layers = ['VCL-clip-element-', 'VCL-buffer-stroke-', 'VCL-buffer-stroke-']; layers.forEach(layer => { const targetId = '#' + layer + baseId; let target = select(targetId); if (target.size()) { if (duration) { target = target.transition(attribute).duration(duration); if (easing) { target = target.ease(easing); } } target.attr(attribute, newValue); } }); }; const applyDefaults = (selection, className) => { selection .attr('class', className + '-highlight ' + className + '-hover') .attr('focusable', false) .attr('aria-label', null) .attr('aria-hidden', true) .attr('role', null) .style('pointer-events', 'none') .attr('tabindex', null) .attr('mix-blend-mode', null) .style('mix-blend-mode', null); }; const applyOutlineOverride = (selection, extraStrokeWidth, url, buffer, dash) => { selection .style('stroke-linecap', 'butt') .style('outline-offset', '0px') .style('outline-color', 'none') .style('outline-width', '0px') .attr('fill', 'none') .style('fill', 'none') .style('stroke-opacity', 1) .attr('marker-start', null) .attr('marker-end', null) .attr('filter', null) .attr('stroke-dasharray', dash ? '8 6' : null) .attr('clip-path', url) .style('stroke-width', (_, i, n) => { const scaleIndex = select(n[i]).attr('transform') ? select(n[i]) .attr('transform') .indexOf('scale') : -1; let scale = 1; if (scaleIndex > -1) { const scaleSubstring = select(n[i]) .attr('transform') .substring(scaleIndex + 6); const endSubstring = scaleSubstring.indexOf(',') < scaleSubstring.indexOf(')') && scaleSubstring.indexOf(',') !== -1 ? scaleSubstring.indexOf(',') : scaleSubstring.indexOf(')'); scale = +scaleSubstring.substring(0, endSubstring); } return ((buffer ? 2 : 0) + extraStrokeWidth * 2) / scale + 'px'; }); }; const createId = (id, key) => { const parsedKey = key instanceof Date ? key.getTime() : key; return id + '-' + (parsedKey + '').replace(/\W/g, '-'); };
the_stack
import * as path from "path"; import * as vscode from "vscode"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError"; import { ConfigKey, EventNames, FileNames, ScaffoldType } from "../constants"; import { FileUtility } from "../FileUtility"; import { TelemetryContext, TelemetryWorker } from "../telemetry"; import * as utils from "../utils"; import { checkAzureLogin } from "./Apis"; import { Compilable } from "./Interfaces/Compilable"; import { Component, ComponentType } from "./Interfaces/Component"; import { Deployable } from "./Interfaces/Deployable"; import { Device } from "./Interfaces/Device"; import { ProjectHostType } from "./Interfaces/ProjectHostType"; import { ProjectTemplateType, TemplateFileInfo } from "./Interfaces/ProjectTemplate"; import { Provisionable } from "./Interfaces/Provisionable"; import { Uploadable } from "./Interfaces/Uploadable"; import { DirectoryNotFoundError } from "../common/Error/OperationFailedErrors/DirectoryNotFoundError"; const importLazy = require("import-lazy"); const azureUtilityModule = importLazy(() => require("./AzureUtility"))(); export enum OpenScenario { createNewProject, configureProject } export abstract class IoTWorkbenchProjectBase { protected extensionContext: vscode.ExtensionContext; protected channel: vscode.OutputChannel; protected telemetryContext: TelemetryContext; protected projectRootPath = ""; protected iotWorkbenchProjectFilePath = ""; protected componentList: Component[]; protected projectHostType: ProjectHostType = ProjectHostType.Unknown; /** * projectHostType config is recoreded in iot workbench project file * @param scaffoldType * @param projectFileRootPath */ static async getProjectType( scaffoldType: ScaffoldType, projectFileRootPath: string | undefined ): Promise<ProjectHostType> { if (!projectFileRootPath) { return ProjectHostType.Unknown; } const iotWorkbenchProjectFile = path.join(projectFileRootPath, FileNames.iotWorkbenchProjectFileName); if (!(await FileUtility.fileExists(scaffoldType, iotWorkbenchProjectFile))) { return ProjectHostType.Unknown; } const iotWorkbenchProjectFileString = ((await FileUtility.readFile( scaffoldType, iotWorkbenchProjectFile, "utf8" )) as string).trim(); if (iotWorkbenchProjectFileString) { const projectConfig = JSON.parse(iotWorkbenchProjectFileString); if (projectConfig && projectConfig[`${ConfigKey.projectHostType}`] !== undefined) { const projectHostType: ProjectHostType = utils.getEnumKeyByEnumValue( ProjectHostType, projectConfig[`${ConfigKey.projectHostType}`] ); return projectHostType; } } // TODO: For backward compatibility, will remove later const devcontainerFolderPath = path.join(projectFileRootPath, FileNames.devcontainerFolderName); if (await FileUtility.directoryExists(scaffoldType, devcontainerFolderPath)) { return ProjectHostType.Container; } else { return ProjectHostType.Workspace; } } canProvision(comp: {}): comp is Provisionable { return (comp as Provisionable).provision !== undefined; } canDeploy(comp: {}): comp is Deployable { return (comp as Deployable).deploy !== undefined; } canCompile(comp: {}): comp is Compilable { return (comp as Compilable).compile !== undefined; } canUpload(comp: {}): comp is Uploadable { return (comp as Uploadable).upload !== undefined; } constructor(context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext) { this.componentList = []; this.extensionContext = context; this.channel = channel; this.telemetryContext = telemetryContext; } abstract async load(scaffoldType: ScaffoldType, initLoad?: boolean): Promise<void>; abstract async create( templateFilesInfo: TemplateFileInfo[], projectType: ProjectTemplateType, boardId: string, openInNewWindow: boolean ): Promise<void>; async compile(): Promise<boolean> { for (const item of this.componentList) { if (this.canCompile(item)) { await item.checkPrerequisites("compile device code"); const res = await item.compile(); if (!res) { vscode.window.showErrorMessage("Unable to compile the device code, please check output window for detail."); } } } return true; } async upload(): Promise<boolean> { for (const item of this.componentList) { if (this.canUpload(item)) { await item.checkPrerequisites("upload device code"); const res = await item.upload(); if (!res) { vscode.window.showErrorMessage("Unable to upload the sketch, please check output window for detail."); } } } return true; } async provision(): Promise<boolean> { const provisionItemList: string[] = []; for (const item of this.componentList) { if (this.canProvision(item)) { await item.checkPrerequisites("provision"); provisionItemList.push(item.name); } } if (provisionItemList.length === 0) { // nothing to provision: vscode.window.showInformationMessage("Congratulations! There is no Azure service to provision in this project."); return false; } // Ensure azure login before component provision let subscriptionId: string | undefined = ""; let resourceGroup: string | undefined = ""; if (provisionItemList.length > 0) { await checkAzureLogin(); azureUtilityModule.AzureUtility.init(this.extensionContext, this.projectRootPath, this.channel); resourceGroup = await azureUtilityModule.AzureUtility.getResourceGroup(); subscriptionId = azureUtilityModule.AzureUtility.subscriptionId; if (!resourceGroup || !subscriptionId) { return false; } } else { return false; } for (const item of this.componentList) { const _provisionItemList: string[] = []; if (this.canProvision(item)) { for (let i = 0; i < provisionItemList.length; i++) { if (provisionItemList[i] === item.name) { _provisionItemList[i] = `>> ${i + 1}. ${provisionItemList[i]}`; } else { _provisionItemList[i] = `${i + 1}. ${provisionItemList[i]}`; } } const selection = await vscode.window.showQuickPick( [ { label: _provisionItemList.join(" - "), description: "", detail: "Click to continue" } ], { ignoreFocusOut: true, placeHolder: "Provision process" } ); if (!selection) { return false; } const res = await item.provision(); if (!res) { throw new OperationCanceledError("Provision cancelled."); } } } return true; } async deploy(): Promise<void> { let azureLoggedIn = false; const deployItemList: string[] = []; for (const item of this.componentList) { if (this.canDeploy(item)) { await item.checkPrerequisites("deploy device code"); deployItemList.push(item.name); } } if (deployItemList && deployItemList.length <= 0) { await vscode.window.showInformationMessage( "Congratulations! The project does not contain any Azure components to be deployed." ); return; } if (!azureLoggedIn) { azureLoggedIn = await checkAzureLogin(); } for (const item of this.componentList) { const _deployItemList: string[] = []; if (this.canDeploy(item)) { for (let i = 0; i < deployItemList.length; i++) { if (deployItemList[i] === item.name) { _deployItemList[i] = `>> ${i + 1}. ${deployItemList[i]}`; } else { _deployItemList[i] = `${i + 1}. ${deployItemList[i]}`; } } const selection = await vscode.window.showQuickPick( [ { label: _deployItemList.join(" - "), description: "", detail: "Click to continue" } ], { ignoreFocusOut: true, placeHolder: "Deploy process" } ); if (!selection) { throw new OperationCanceledError(`Component deployment cancelled.`); } const res = await item.deploy(); if (!res) { throw new OperationFailedError("deploy iot workbench project", `Failed to deploy component ${item.name}`, ""); } } } vscode.window.showInformationMessage("Azure deploy succeeded."); } /** * Configure project environment: Scaffold configuration files with the given * template files. */ async configureProjectEnvironmentCore(deviceRootPath: string, scaffoldType: ScaffoldType): Promise<void> { for (const component of this.componentList) { if (component.getComponentType() === ComponentType.Device) { const device = component as Device; await device.configDeviceEnvironment(deviceRootPath, scaffoldType); } } } abstract async openProject( scaffoldType: ScaffoldType, openInNewWindow: boolean, openScenario: OpenScenario ): Promise<void>; async configDeviceSettings(): Promise<boolean> { for (const component of this.componentList) { if (component.getComponentType() === ComponentType.Device) { const device = component as Device; await device.configDeviceSettings(); } } return true; } /** * Send telemetry when the IoT project is load when VS Code opens */ sendLoadEventTelemetry(context: vscode.ExtensionContext): void { const telemetryWorker = TelemetryWorker.getInstance(context); try { telemetryWorker.sendEvent(EventNames.projectLoadEvent, this.telemetryContext); } catch { // If sending telemetry failed, skip the error to avoid blocking user. } } /** * Validate whether project root path exists. If not, throw error. * @param scaffoldType scaffold type */ async validateProjectRootPathExists(operation: string, scaffoldType: ScaffoldType): Promise<void> { if (!(await FileUtility.directoryExists(scaffoldType, this.projectRootPath))) { throw new DirectoryNotFoundError( operation, `project root path ${this.projectRootPath}`, "Please initialize the project first." ); } } }
the_stack
import type { PartialDeep } from 'type-fest' import deepmerge from 'deepmerge'; // eslint-disable-next-line no-restricted-imports import type { Color as MuiColorShades } from '@material-ui/core'; // // All About the Themes, the Theme Palette and Colors // ================================================== // There are two themes active at a time: the user theme and the site theme. The // user theme is a user-configurable preference representing whether to use // light mode, dark mode, etc. The site theme represents the styling differences // between LessWrong, EA Forum, Alignment Forum, Progress Studies Forum, and // whatever other sites share the codebase. // // The palette is constructed in two parts: the shade palette // (ThemeShadePalette) and the component palette (ThemeComponentPalette). Colors // in the component palette may depend on colors/functions in the shade palette // (but not vise versa). These are merged together to create the overall theme. // // Components Should Use the Palette // ================================= // When writing styles for UI components, use colors that come from the palette, // rather than writing the color directly, eg like this: // // const styles = (theme: ThemeType): JssStyles => ({ // normalText: { // color: theme.palette.text.normal, // }, // notice: { // border: theme.palette.border.normal, // background: theme.palette.panelBackground.default, // }, // }); // // Not like this: // // const styles = (theme: ThemeType): JssStyles => ({ // normalText: { // color: "rgba(0,0,0,.87)", // Bad: Will be black-on-black in dark mode // }, // notice: { // border: "rgba(0,0,0,.1)", // Bad: Border will be black-on-black // background: "#fff", // Bad: Text will be white-on-white // }, // }); // // This is enforced by a unit test, which will provide a theme with blanked-out // palette colors and scan JSS styles for color words. Following this convention // should prevent almost all problems with dark-on-dark and light-on-light text. // However tooltips and buttons are occasionally inverted relative to the base // theme, and aesthetic issues may appear in dark mode that don't appear in // light mode and vise versa, so try to check your UI in both. // // If you can't find the color you want, go ahead and add it! Having to add // colors to the palette is meant to make sure you give a little thought to // themes and dark mode, not to restrict you to approved colors. First add your // color to ThemeType in themeType.ts. This will create type errors in all the // other places you need to add the color (currently defaultPalette.ts and // darkMode.ts). // // Text Color and Alpha Versus Shade // ================================= // When you've got dark text on a white background, there are two ways to adjust // its contrast: either choose a shade of grey, or make it black and choose an // opacity (aka alpha). In general, opacity is the better option, because it // maintains the ~same contrast ratio if you put you put the same text color // on a colored background. The same applies for dark-mode themes, where it's // better to use white-and-transparent rather than grey. // // Don't overuse pure-black or pure-white text colors. Think of these as // bolded colors, not as defaults. // // Text should have a minimum contrast ratio of 4.5:1 ("AA") and ideally 7:1 // ("AAA"). You can check the contrast ratio of your text in the Chrome // development tools. In the Elements tab, find the `color` attribute on an // element with text, click on the swatch next to it, and the contrast ratio // should be on the color-picker dialog that appears. // // Notational Conventions // ====================== // CSS has a number of different ways to specify colors. For the sake of // consistency, we only use a subset of them. // // Do Use: // Three or six hex digits: #rrggbb // RGB 0-255 with alpha 0-1: "rgba(r,g,b,a)", // Avoid: // Any color words (including "black" and "white"). If used in the theme in // a place where material-UI uses them, material-UI will crash. // // HSL, HSLA, HWB, Lab, and LCH color specifiers, eg "hsl(60 100% 50%)" // Functional notation without commas, eg "rgba(0 0 0 / 10%)" // RGB percentages, eg "rgba(50%,25%,25%,1)" // Omitted alpha: eg "rgb(0,0,100)" // Importing color constants from @material-ui/core/colors or other libraries // Color keywords other than white, black, and transparent: eg "red", "grey", "wheat" // // export const grey = { // Exactly matches @material-ui/core/colors/grey 50: '#fafafa', 100: '#f5f5f5', 200: '#eeeeee', 300: '#e0e0e0', 400: '#bdbdbd', 500: '#9e9e9e', 600: '#757575', 700: '#616161', 800: '#424242', 900: '#212121', A100: '#d5d5d5', A200: '#aaaaaa', A400: '#303030', A700: '#616161', // Greyscale colors not in the MUI palette 0: "#fff", 1000: "#000", 10: '#fefefe', 20: '#fdfdfd', 25: '#fcfcfc', 30: '#fbfbfb', 55: '#f9f9f9', 60: '#f8f8f8', 110: "#f3f3f3", 120: '#f2f2f2', 140: "#f0f0f0", 250: "#e8e8e8", 310: "#dddddd", 315: "#d4d4d4", 320: "#d9d9d9", 340: "#d0d0d0", 405: "#bbbbbb", 410: "#b3b3b3", 550: "#999999", 620: "#888888", 650: "#808080", 680: "#666666", 710: "#606060", 750: "#5e5e5e", } export const defaultShadePalette = (): ThemeShadePalette => { const greyAlpha = (alpha: number) => `rgba(0,0,0,${alpha})`; return { grey, greyAlpha, boxShadowColor: (alpha: number) => greyAlpha(alpha), greyBorder: (thickness: string, alpha: number) => `${thickness} solid ${greyAlpha(alpha)}`, fonts: { // Every site theme overrides these sansSerifStack: "sans-serif", serifStack: "serif", }, type: "light", } } export const defaultComponentPalette = (shades: ThemeShadePalette): ThemeComponentPalette => ({ text: { primary: shades.greyAlpha(.87), secondary: shades.greyAlpha(.54), normal: shades.greyAlpha(.87), maxIntensity: shades.greyAlpha(1.0), slightlyIntense: shades.greyAlpha(.92), slightlyIntense2: shades.greyAlpha(.9), slightlyDim: shades.greyAlpha(.8), slightlyDim2: shades.greyAlpha(.7), dim: shades.greyAlpha(.5), dim2: shades.grey[800], dim3: shades.grey[600], dim4: shades.grey[500], dim700: shades.grey[700], dim40: shades.greyAlpha(.4), dim45: shades.greyAlpha(.45), dim55: shades.greyAlpha(.55), dim60: shades.greyAlpha(.6), grey: shades.grey[650], spoilerBlockNotice: "#fff", notificationCount: shades.greyAlpha(0.6), notificationLabel: shades.greyAlpha(.66), eventType: "#c0a688", tooltipText: "#fff", negativeKarmaRed: "#ff8a80", moderationGuidelinesEasygoing: 'rgba(100, 169, 105, 0.9)', moderationGuidelinesNormEnforcing: '#2B6A99', moderationGuidelinesReignOfTerror: 'rgba(179,90,49,.8)', charsAdded: "#008800", charsRemoved: "#880000", invertedBackgroundText: "#fff", invertedBackgroundText2: "rgba(255,255,255,0.7)", invertedBackgroundText3: "rgba(255,255,255,0.5)", invertedBackgroundText4: "rgba(255,255,255,0.8)", error: "#9b5e5e", error2: "#E04E4B", red: "#ff0000", sequenceIsDraft: "rgba(100, 169, 105, 0.9)", sequenceTitlePlaceholder: "rgba(255,255,255,.5)", reviewUpvote: "rgba(70,125,70, .87)", reviewDownvote: "rgba(125,70,70, .87)", aprilFools: { orange: "#e64a19", yellow: "#f57f17", green: "#1b5e20", }, }, link: { unmarked: shades.greyAlpha(.87), dim: shades.greyAlpha(.5), dim2: shades.grey[600], dim3: shades.greyAlpha(.4), grey800: shades.grey[800], tocLink: shades.grey[600], tocLinkHighlighted: shades.grey[1000], }, linkHover: { dim: shades.greyAlpha(.3), }, icon: { normal: shades.greyAlpha(.87), maxIntensity: shades.greyAlpha(1.0), slightlyDim: shades.greyAlpha(.8), slightlyDim2: shades.greyAlpha(.75), slightlyDim3: shades.greyAlpha(.7), slightlyDim4: shades.greyAlpha(.6), dim: shades.greyAlpha(.5), dim2: shades.greyAlpha(.4), dim3: shades.grey[400], dim4: shades.grey[500], dim5: shades.greyAlpha(.3), dim6: shades.greyAlpha(.2), dim55: shades.greyAlpha(.55), dim600: shades.grey[600], dim700: shades.grey[700], tooltipUserMetric: "rgba(255,255,255,.8)", loadingDots: shades.greyAlpha(.55), loadingDotsAlternate: shades.grey[0], horizRuleDots: shades.greyAlpha(.26), greenCheckmark: "#4caf50", onTooltip: "#fff", inverted: shades.grey[0], topAuthor: shades.grey[340], navigationSidebarIcon: shades.greyAlpha(1.0), commentsBubble: { commentCount: "#fff", noUnread: shades.greyAlpha(.22), newPromoted: "rgb(160, 225, 165)", }, }, border: { normal: shades.greyBorder("1px", .2), itemSeparatorBottom: shades.greyBorder("2px", .05), slightlyFaint: shades.greyBorder("1px", .15), slightlyIntense: shades.greyBorder("1px", .25), slightlyIntense2: shades.greyBorder("1px", .3), slightlyIntense3: shades.greyBorder("1px", .4), intense: shades.greyBorder("2px", .5), faint: shades.greyBorder("1px", .1), extraFaint: shades.greyBorder("1px", .08), grey300: `1px solid ${shades.grey[300]}`, grey400: `1px solid ${shades.grey[400]}`, maxIntensity: shades.greyBorder("1px", 1.0), tableHeadingDivider: shades.greyBorder("2px", 1.0), table: `1px double ${shades.grey[410]}`, tableCell: `1px double ${shades.grey[320]}`, transparent: shades.greyBorder("1px", 0.0), emailHR: "1px solid #aaa", sunshineNewUsersInfoHR: "1px solid #ccc", appBarSubtitleDivider: `1px solid ${shades.grey[400]}`, commentBorder: "1px solid rgba(72,94,144,0.16)", answerBorder: "2px solid rgba(72,94,144,0.16)", tooltipHR: "solid 1px rgba(255,255,255,.2)", }, background: { default: shades.grey[60], paper: shades.grey[0], //Used by MUI pageActiveAreaBackground: shades.grey[0], diffInserted: "#d4ead4", diffDeleted: "#f0d3d3", usersListItem: shades.greyAlpha(.05), }, panelBackground: { default: shades.grey[0], translucent: "rgba(255,255,255,.87)", translucent2: "rgba(255,255,255,.8)", translucent3: "rgba(255,255,255,.75)", hoverHighlightGrey: shades.greyAlpha(.1), postsItemHover: shades.grey[50], formErrors: shades.greyAlpha(0.25), darken02: shades.greyAlpha(.02), darken03: shades.greyAlpha(.03), darken04: shades.greyAlpha(.04), darken05: shades.greyAlpha(.05), darken08: shades.greyAlpha(.08), darken10: shades.greyAlpha(.1), darken15: shades.greyAlpha(.15), darken20: shades.greyAlpha(.2), darken25: shades.greyAlpha(.25), darken40: shades.greyAlpha(.4), adminHomeRecentLogins: "rgba(50,100,50,.1)", adminHomeAllUsers: "rgba(100,50,50,.1)", deletedComment: "#ffefef", newCommentFormModerationGuidelines: shades.greyAlpha(.07), commentNodeEven: shades.grey[120], commentNodeOdd: shades.grey[25], commentModeratorHat: "#5f9b651c", commentHighlightAnimation: shades.grey[300], postsItemExpandedComments: shades.grey[50], metaculusBackground: "#2c3947", spoilerBlock: "#000", revealedSpoilerBlock: shades.greyAlpha(.12), tableHeading: shades.grey[50], notificationMenuTabBar: shades.grey[100], recentDiscussionThread: shades.grey[20], tooltipBackground: "rgba(75,75,75,.94)", tenPercent: shades.greyAlpha(.1), sunshineReportedContent: "rgba(60,0,0,.08)", sunshineFlaggedUser: "rgba(150,0,0,.05)", sunshineNewPosts: "rgba(0,80,0,.08)", sunshineNewComments: "rgba(120,120,0,.08)", sunshineNewTags: "rgba(80,80,0,.08)", sunshineWarningHighlight: "rgba(255,50,0,.2)", mobileNavFooter: shades.grey[0], singleLineComment: shades.grey[140], singleLineCommentHovered: shades.grey[300], singleLineCommentOddHovered: shades.grey[110], sequenceImageGradient: 'linear-gradient(to top, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.2) 42%, rgba(255, 255, 255, 0) 100%)', sequencesBanner: shades.greyAlpha(.5), }, boxShadow: { default: `0 1px 5px ${shades.boxShadowColor(.025)}`, moreFocused: `0 1px 3px ${shades.boxShadowColor(.1)}`, faint: `0 1px 5px ${shades.boxShadowColor(.1)}`, notificationsDrawer: `${shades.boxShadowColor(.16)} 0px 3px 10px, ${shades.boxShadowColor(.23)} 0px 3px 10px`, appBar: `0 1px 1px ${shades.boxShadowColor(.05)}, 0 1px 1px ${shades.boxShadowColor(.05)}`, sequencesGridItemHover: `0 1px 3px ${shades.boxShadowColor(.1)}`, eventCard: `0 1px 3px ${shades.boxShadowColor(.1)}`, mozillaHubPreview: `0px 0px 10px ${shades.boxShadowColor(.1)}`, featuredResourcesCard: `0 4px 4px ${shades.boxShadowColor(.07)}`, spreadsheetPage1: `2px 0 2px -1px ${shades.boxShadowColor(.15)}`, spreadsheetPage2: `0 0 3px ${shades.boxShadowColor(.3)}`, collectionsCardHover: `0 0 3px ${shades.boxShadowColor(.1)}`, comment: `0 0 10px ${shades.boxShadowColor(.2)}`, sunshineSidebarHoverInfo: `-3px 0 5px 0px ${shades.boxShadowColor(.1)}`, sunshineSendMessage: `0 0 10px ${shades.boxShadowColor(.5)}`, lwCard: `0 0 10px ${shades.boxShadowColor(.2)}`, searchResults: `0 0 20px ${shades.boxShadowColor(.2)}`, recentDiscussionMeetupsPoke: `5px 5px 5px ${shades.boxShadowColor(.2)}`, }, buttons: { hoverGrayHighlight: shades.greyAlpha(0.05), startReadingButtonBackground: shades.greyAlpha(0.05), recentDiscussionSubscribeButtonText: "#fff", featuredResourceCTAtext: "#fff", primaryDarkText: "#fff", feedExpandButton: { background: "#fff", plusSign: "#666", border: "1px solid #ddd", }, notificationsBellOpen: { background: shades.greyAlpha(0.4), icon: shades.grey[0], }, groupTypesMultiselect: { background: "rgba(100,169,105, 0.9)", hoverBackground: "rgba(100,169,105, 0.5)", }, imageUpload: { background: shades.greyAlpha(.5), hoverBackground: shades.greyAlpha(.35), }, bookCheckoutButton: "#53a55a", eventCardTag: "#CC5500", }, tag: { background: shades.grey[200], border: `solid 1px ${shades.grey[200]}`, coreTagBorder: shades.greyBorder("1px", .12), text: shades.greyAlpha(.9), boxShadow: `1px 2px 5px ${shades.boxShadowColor(.2)}`, hollowTagBackground: shades.grey[0], addTagButtonBackground: shades.grey[300], }, geosuggest: { dropdownText: "#000", dropdownBackground: "#fff", dropdownActiveBackground: "#267dc0", dropdownActiveText: "#fff", dropdownHoveredBackground: "#f5f5f5", dropdownActiveHoveredBackground: "#ccc", }, review: { activeProgress: 'rgba(127, 175, 131, 0.5)', progressBar: 'rgba(127, 175, 131, 0.7)', adminButton: "rgba(200,150,100)", }, header: { text: shades.greyAlpha(.87), background: shades.grey[30], }, datePicker: { selectedDate: "#428bca", }, commentParentScrollerHover: shades.greyAlpha(.075), tocScrollbarColors: `rgba(255,255,255,0) ${shades.grey[300]}`, eventsHomeLoadMoreHover: '#085d6c', eaForumGroupsMobileImg: '#e2f1f4', contrastText: shades.grey[0], event: '#2b6a99', group: '#588f27', individual: '#3f51b5', primary: { main: "#5f9b65", dark: "#426c46", light: "#7faf83", contrastText: shades.grey[0], }, secondary: { main: "#5f9b65", dark: "#426c46", light: "#7faf83", contrastText: shades.grey[0], }, lwTertiary: { main: "#69886e", dark: "#21672b", }, error: { main: "#bf360c", dark: "#852508", light: "#cb5e3c", contrastText: shades.grey[0], }, })
the_stack
import { base64ToBin } from '../../format/format'; import { CompressionFlag, ContextFlag, Secp256k1Wasm, } from './secp256k1-wasm-types'; import { secp256k1Base64Bytes } from './secp256k1.base64'; export { ContextFlag, CompressionFlag, Secp256k1Wasm }; /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */ const wrapSecp256k1Wasm = ( instance: WebAssembly.Instance, heapU8: Uint8Array, heapU32: Uint32Array ): Secp256k1Wasm => ({ contextCreate: (context) => (instance.exports as any)._secp256k1_context_create(context), contextRandomize: (contextPtr, seedPtr) => (instance.exports as any)._secp256k1_context_randomize(contextPtr, seedPtr), free: (pointer) => (instance.exports as any)._free(pointer), heapU32, heapU8, instance, malloc: (bytes) => (instance.exports as any)._malloc(bytes), mallocSizeT: (num) => { // eslint-disable-next-line @typescript-eslint/no-magic-numbers const pointer = (instance.exports as any)._malloc(4); // eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers const pointerView32 = pointer >> 2; // eslint-disable-next-line functional/no-expression-statement heapU32.set([num], pointerView32); return pointer; }, mallocUint8Array: (array) => { const pointer = (instance.exports as any)._malloc(array.length); // eslint-disable-next-line functional/no-expression-statement heapU8.set(array, pointer); return pointer; }, privkeyTweakAdd: (contextPtr, secretKeyPtr, tweakNum256Ptr) => (instance.exports as any)._secp256k1_ec_privkey_tweak_add( contextPtr, secretKeyPtr, tweakNum256Ptr ), privkeyTweakMul: (contextPtr, secretKeyPtr, tweakNum256Ptr) => (instance.exports as any)._secp256k1_ec_privkey_tweak_mul( contextPtr, secretKeyPtr, tweakNum256Ptr ), pubkeyCreate: (contextPtr, publicKeyPtr, secretKeyPtr) => (instance.exports as any)._secp256k1_ec_pubkey_create( contextPtr, publicKeyPtr, secretKeyPtr ), pubkeyParse: ( contextPtr, publicKeyOutPtr, publicKeyInPtr, publicKeyInLength ) => (instance.exports as any)._secp256k1_ec_pubkey_parse( contextPtr, publicKeyOutPtr, publicKeyInPtr, publicKeyInLength ), pubkeySerialize: ( contextPtr, outputPtr, outputLengthPtr, publicKeyPtr, compression ) => (instance.exports as any)._secp256k1_ec_pubkey_serialize( contextPtr, outputPtr, outputLengthPtr, publicKeyPtr, compression ), pubkeyTweakAdd: (contextPtr, publicKeyPtr, tweakNum256Ptr) => (instance.exports as any)._secp256k1_ec_pubkey_tweak_add( contextPtr, publicKeyPtr, tweakNum256Ptr ), pubkeyTweakMul: (contextPtr, publicKeyPtr, tweakNum256Ptr) => (instance.exports as any)._secp256k1_ec_pubkey_tweak_mul( contextPtr, publicKeyPtr, tweakNum256Ptr ), readHeapU8: (pointer, bytes) => new Uint8Array(heapU8.buffer, pointer, bytes), readSizeT: (pointer) => { // eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers const pointerView32 = pointer >> 2; return heapU32[pointerView32]; }, recover: (contextPtr, outputPubkeyPointer, rSigPtr, msg32Ptr) => (instance.exports as any)._secp256k1_ecdsa_recover( contextPtr, outputPubkeyPointer, rSigPtr, msg32Ptr ), recoverableSignatureParse: (contextPtr, outputRSigPtr, inputSigPtr, rid) => (instance.exports as any)._secp256k1_ecdsa_recoverable_signature_parse_compact( contextPtr, outputRSigPtr, inputSigPtr, rid ), recoverableSignatureSerialize: ( contextPtr, sigOutPtr, recIDOutPtr, rSigPtr ) => (instance.exports as any)._secp256k1_ecdsa_recoverable_signature_serialize_compact( contextPtr, sigOutPtr, recIDOutPtr, rSigPtr ), schnorrSign: (contextPtr, outputSigPtr, msg32Ptr, secretKeyPtr) => (instance.exports as any)._secp256k1_schnorr_sign( contextPtr, outputSigPtr, msg32Ptr, secretKeyPtr ), schnorrVerify: (contextPtr, sigPtr, msg32Ptr, publicKeyPtr) => (instance.exports as any)._secp256k1_schnorr_verify( contextPtr, sigPtr, msg32Ptr, publicKeyPtr ), seckeyVerify: (contextPtr, secretKeyPtr) => (instance.exports as any)._secp256k1_ec_seckey_verify( contextPtr, secretKeyPtr ), sign: (contextPtr, outputSigPtr, msg32Ptr, secretKeyPtr) => (instance.exports as any)._secp256k1_ecdsa_sign( contextPtr, outputSigPtr, msg32Ptr, secretKeyPtr ), signRecoverable: (contextPtr, outputRSigPtr, msg32Ptr, secretKeyPtr) => (instance.exports as any)._secp256k1_ecdsa_sign_recoverable( contextPtr, outputRSigPtr, msg32Ptr, secretKeyPtr ), signatureMalleate: (contextPtr, outputSigPtr, inputSigPtr) => (instance.exports as any)._secp256k1_ecdsa_signature_malleate( contextPtr, outputSigPtr, inputSigPtr ), signatureNormalize: (contextPtr, outputSigPtr, inputSigPtr) => (instance.exports as any)._secp256k1_ecdsa_signature_normalize( contextPtr, outputSigPtr, inputSigPtr ), signatureParseCompact: (contextPtr, sigOutPtr, compactSigInPtr) => (instance.exports as any)._secp256k1_ecdsa_signature_parse_compact( contextPtr, sigOutPtr, compactSigInPtr ), signatureParseDER: (contextPtr, sigOutPtr, sigDERInPtr, sigDERInLength) => (instance.exports as any)._secp256k1_ecdsa_signature_parse_der( contextPtr, sigOutPtr, sigDERInPtr, sigDERInLength ), signatureSerializeCompact: (contextPtr, outputCompactSigPtr, inputSigPtr) => (instance.exports as any)._secp256k1_ecdsa_signature_serialize_compact( contextPtr, outputCompactSigPtr, inputSigPtr ), signatureSerializeDER: ( contextPtr, outputDERSigPtr, outputDERSigLengthPtr, inputSigPtr ) => (instance.exports as any)._secp256k1_ecdsa_signature_serialize_der( contextPtr, outputDERSigPtr, outputDERSigLengthPtr, inputSigPtr ), verify: (contextPtr, sigPtr, msg32Ptr, pubkeyPtr) => (instance.exports as any)._secp256k1_ecdsa_verify( contextPtr, sigPtr, msg32Ptr, pubkeyPtr ), }); /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */ /* eslint-disable functional/immutable-data, functional/no-expression-statement, @typescript-eslint/no-magic-numbers, functional/no-conditional-statement, no-bitwise, functional/no-throw-statement */ /** * Method extracted from Emscripten's preamble.js */ const isLittleEndian = (buffer: ArrayBuffer): boolean => { const littleEndian = true; const notLittleEndian = false; const heap16 = new Int16Array(buffer); const heap32 = new Int32Array(buffer); const heapU8 = new Uint8Array(buffer); heap32[0] = 1668509029; heap16[1] = 25459; return heapU8[2] !== 115 || heapU8[3] !== 99 ? /* istanbul ignore next */ notLittleEndian : littleEndian; }; /** * Method derived from Emscripten's preamble.js */ const alignMemory = (factor: number, size: number) => Math.ceil(size / factor) * factor; /** * The most performant way to instantiate secp256k1 functionality. To avoid * using Node.js or DOM-specific APIs, you can use `instantiateSecp256k1`. * * Note, most of this method is translated and boiled-down from Emscripten's * preamble.js. Significant changes to the WASM build or breaking updates to * Emscripten will likely require modifications to this method. * * @param webassemblyBytes - A buffer containing the secp256k1 binary. */ export const instantiateSecp256k1WasmBytes = async ( webassemblyBytes: ArrayBuffer ): Promise<Secp256k1Wasm> => { const STACK_ALIGN = 16; const GLOBAL_BASE = 1024; const WASM_PAGE_SIZE = 65536; const TOTAL_STACK = 5242880; const TOTAL_MEMORY = 16777216; const wasmMemory = new WebAssembly.Memory({ initial: TOTAL_MEMORY / WASM_PAGE_SIZE, maximum: TOTAL_MEMORY / WASM_PAGE_SIZE, }); /* istanbul ignore if */ if (!isLittleEndian(wasmMemory.buffer)) { /* * note: this block is excluded from test coverage. It's A) hard to test * (must be either tested on big-endian hardware or a big-endian buffer * mock) and B) extracted from Emscripten's preamble.js, where it should * be tested properly. */ throw new Error('Runtime error: expected the system to be little-endian.'); } const STATIC_BASE = GLOBAL_BASE; const STATICTOP_INITIAL = STATIC_BASE + 67696 + 16; const DYNAMICTOP_PTR = STATICTOP_INITIAL; const DYNAMICTOP_PTR_SIZE = 4; const STATICTOP = (STATICTOP_INITIAL + DYNAMICTOP_PTR_SIZE + 15) & -16; const STACKTOP = alignMemory(STACK_ALIGN, STATICTOP); const STACK_BASE = STACKTOP; const STACK_MAX = STACK_BASE + TOTAL_STACK; const DYNAMIC_BASE = alignMemory(STACK_ALIGN, STACK_MAX); const heapU8 = new Uint8Array(wasmMemory.buffer); const heap32 = new Int32Array(wasmMemory.buffer); const heapU32 = new Uint32Array(wasmMemory.buffer); heap32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE; const TABLE_SIZE = 6; const MAX_TABLE_SIZE = 6; // eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations let getErrNoLocation: (() => number) | undefined; /* * note: A number of methods below are excluded from test coverage. They are * a) not part of the regular usage of this library (should only be evaluated * if the consumer mis-implements the library and exist only to make * debugging easier) and B) already tested adequately in Emscripten, from * which this section is extracted. */ const env = { DYNAMICTOP_PTR, STACKTOP, ___setErrNo: /* istanbul ignore next */ (value: number) => { if (getErrNoLocation !== undefined) { heap32[getErrNoLocation() >> 2] = value; } return value; }, _abort: /* istanbul ignore next */ (err = 'Secp256k1 Error') => { throw new Error(err); }, // eslint-disable-next-line camelcase _emscripten_memcpy_big: /* istanbul ignore next */ ( dest: number, src: number, num: number ) => { heapU8.set(heapU8.subarray(src, src + num), dest); return dest; }, abort: /* istanbul ignore next */ (err = 'Secp256k1 Error') => { throw new Error(err); }, abortOnCannotGrowMemory: /* istanbul ignore next */ () => { throw new Error('Secp256k1 Error: abortOnCannotGrowMemory was called.'); }, enlargeMemory: /* istanbul ignore next */ () => { throw new Error('Secp256k1 Error: enlargeMemory was called.'); }, getTotalMemory: () => TOTAL_MEMORY, }; const info = { env: { ...env, memory: wasmMemory, memoryBase: STATIC_BASE, table: new WebAssembly.Table({ element: 'anyfunc', initial: TABLE_SIZE, maximum: MAX_TABLE_SIZE, }), tableBase: 0, }, global: { Infinity, NaN }, }; return WebAssembly.instantiate(webassemblyBytes, info).then((result) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment getErrNoLocation = result.instance.exports.___errno_location as any; return wrapSecp256k1Wasm(result.instance, heapU8, heapU32); }); }; /* eslint-enable functional/immutable-data, functional/no-expression-statement, @typescript-eslint/no-magic-numbers, functional/no-conditional-statement, no-bitwise, functional/no-throw-statement */ export const getEmbeddedSecp256k1Binary = () => base64ToBin(secp256k1Base64Bytes).buffer; /** * An ultimately-portable (but slower) version of `instantiateSecp256k1Bytes` * which does not require the consumer to provide the secp256k1 binary buffer. */ export const instantiateSecp256k1Wasm = async (): Promise<Secp256k1Wasm> => instantiateSecp256k1WasmBytes(getEmbeddedSecp256k1Binary());
the_stack
import {VNode} from 'snabbdom'; import WebComponent from 'webcomponent'; export {h} from 'snabbdom'; export {jsx} from 'snabbdom-jsx-lite'; export class StateStore<State> { constructor(options: {store?: StateStore<State>}); /** A readonly version of controller's state */ get state(): State; /** Update the state by passing in a property bag */ update(props?: Partial<State>): void; /** * @internal Subscribe to state updates via a listener callback. * Only use for rendering and debugging purposes */ subscribeUpdates(listener: (props: Partial<State>) => void): void; /** @internal Unsubscribe the listener callback that was passed to subscribeUpdates */ unsubscribeUpdates(listener: (props: Partial<State>) => void): void; } export class StateController<State> { constructor(options: {store?: StateStore<State>}); /** A readonly version of controller's state */ get state(): State; /** An initial default property bag for the controller's state */ get defaultState(): State; /** Update the state by passing in a property bag */ _update(props?: Partial<State>): void; /** * @internal Subscribe to state updates via a listener callback. * panel component uses this to trigger dom update pipeline * Only use for rendering and debugging purposes */ subscribeUpdates(listener: (props: Partial<State>) => void): void; /** @internal Unsubscribe the listener callback that was passed to subscribeUpdates */ unsubscribeUpdates(listener: (props: Partial<State>) => void): void; } export interface PanelHelpers { [helper: string]: any; } export interface PanelHooks<State> { /** Function called before an update is applied */ preUpdate?: (stateUpdate: Partial<State>) => void; /** Function called after an update is applied */ postUpdate?: (stateUpdate: Partial<State>) => void; [hookName: string]: (params: any) => void; } // this type is not checked in the Component ContextRegistryT, the Component JS manually checks for these properties instead export interface PanelLifecycleContext { // optional callback that executes each time a component using this context is connected to the DOM bindToComponent?(component: Component<any>): void; // optional callback that executes each time a component using this context is disconnected from the DOM unbindFromComponent?(component: Component<any>): void; } export interface ConfigOptions<StateT, AppStateT = unknown, ContextRegistryT = unknown> { /** Function transforming state object to virtual dom tree */ template(scope?: StateT): VNode; /** Component-specific Shadow DOM stylesheet */ css?: string; /** An initial default value for the component's state property */ defaultState?: StateT; /** Default contexts for the component and its descendants to use if no context parent provides them */ defaultContexts?: Partial<ContextRegistryT>; /** Names of contexts for the component to attach and depend upon */ contexts?: Array<keyof ContextRegistryT>; /** * A state object to share with nested descendant components. If not set, root component * shares entire state object with all descendants. Only applicable to app root components. */ appState?: AppStateT; /** Properties and functions injected automatically into template state object */ helpers?: PanelHelpers; /** Extra rendering/lifecycle callbacks */ hooks?: PanelHooks<StateT>; /** Object mapping string route expressions to handler functions */ routes?: {[route: string]: Function}; /** Whether to apply updates to DOM immediately, instead of batching to one update per frame */ updateSync?: boolean; /** Whether to use Shadow DOM */ useShadowDom?: boolean; /** Defines the threshold at which 'slowRender' events will be dispatched, defaults to 20ms */ slowThreshold?: number; } export interface AttrSchema { /** Type of the attribute. One of 'string' | 'number' | 'boolean' | 'json' */ type: string; /** Default value if the attr is not defined */ default?: any; /** Description of attribute, what it does e.t.c */ description?: string; /** Possible values of an attribute. e.g ['primary', 'secondary'] */ enum?: string[]; /** When setAttribute is invoked, console.warn that attr is deprecated e.g 'use xyz instead' */ deprecatedMsg?: string; /** * For a type: `json` attr, the typescript type that corresponds to it. * Can be used to auto-generate Attrs interface */ tsType?: string; /** * Explicitly require an attribute to be passed, useful when no default value can be inferred. */ required?: boolean; } export type AttrsSchema<T> = { [attr in keyof T]: string | AttrSchema; }; export interface AnyAttrs { [attr: string]: any; } export class Component< StateT, AttrsT = AnyAttrs, AppStateT = unknown, AppT = unknown, ContextRegistryT = unknown > extends WebComponent { /** The first Panel Component ancestor in the DOM tree; null if this component is the root */ $panelParent: Component<unknown>; /** * Attributes schema that defines the component's html attributes and their types * Panel auto parses attribute changes into this.attrs object and $attrs template helper */ static get attrsSchema(): {[attr: string]: string | AttrSchema}; /** A reference to the top-level component */ app: AppT; /** State object to share with nested descendant components */ appState: AppStateT; /** Refers to the outer-most element in the template file for shadow DOM components. Otherwise, el refers to the component itself. */ el: HTMLElement; /** A flag that represents whether the component is currently connected and initialized */ initialized: boolean; /** Defines the state of the component, including all the properties required for rendering */ state: StateT; readonly timings: Readonly<{ /** The time in ms that the component constructor ran */ createdAt: number; /** The time in ms that component initialization started (also see 'initializingCompletedAt') */ initializingStartedAt: number; /** The time in ms that component initialization completed (also see 'initializingStartedAt') */ initializingCompletedAt: number; /** The time in ms that the last #attributeChangedCallback ran */ lastAttributeChangedAt: number; /** The time in ms that the last #update ran */ lastUpdateAt: number; /** The time in ms that the last render ran */ lastRenderAt: number; }>; /** Defines standard component configuration */ get config(): ConfigOptions<StateT, AppStateT, ContextRegistryT>; /** * Template helper functions defined in config object, and exposed to template code as $helpers. * This getter uses the component's internal config cache. */ get helpers(): this['config']['helpers']; /** Gets the attribute value. Throws an error if attr not defined in attrsSchema */ attr<A extends keyof AttrsT>(attr: A): AttrsT[A]; /** Attributes parsed from component's html attributes using attrsSchema */ attrs(): AttrsT; /** * For use inside view templates, to create a child Panel component nested under this * component, which will share its state object and update cycle. */ child<T = object>(tagName: string, config?: T): VNode; /** * Searches the component's Panel ancestors for the first component of the * given type (HTML tag name). */ findPanelParentByTagName(tagName: string): Component<any>; /** * Fetches a value from the component's configuration map (a combination of * values supplied in the config() getter and defaults applied automatically). */ getConfig<K extends keyof ConfigOptions<StateT, AppStateT, ContextRegistryT>>(key: K): this['config'][K]; /** Sets a value in the component's configuration map after element initialization */ setConfig<K extends keyof ConfigOptions<StateT, AppStateT, ContextRegistryT>>( key: K, val: ConfigOptions<StateT, AppStateT, ContextRegistryT>[K], ): void; /** * Executes the route handler matching the given URL fragment, and updates * the URL, as though the user had navigated explicitly to that address. */ navigate(fragment: string, stateUpdate?: Partial<StateT>): void; /** Run a user-defined hook with the given parameters */ runHook: ( hookName: keyof ConfigOptions<StateT, AppStateT, ContextRegistryT>['hooks'], options: {cascade: boolean; exclude: Component<any, any>}, params: any, ) => void; /** * To be overridden by subclasses, defining conditional logic for whether * a component should rerender its template given the state to be applied. * In most cases this method can be left untouched, but can provide improved * performance when dealing with very many DOM elements. */ shouldUpdate(state: StateT): boolean; /** * Applies a state update specifically to app state shared across components. * In apps which don't specify `appState` in the root component config, all * state is shared across all parent and child components and the standard * update() method should be used instead. */ updateApp(stateUpdate?: Partial<AppStateT>): void; /** * Applies a state update, triggering a re-render check of the component as * well as any other components sharing the same state. This is the primary * means of updating the DOM in a Panel application. */ update(stateUpdate?: Partial<StateT> | ((state: StateT) => Partial<StateT>)): void; /** * Helper function which will queue a function to be run once the component has been * initialized and added to the DOM. If the component has already had its connectedCallback * run, the function will run immediately. * * It can optionally return a function to be enqueued to be run just before the component is * removed from the DOM. This occurs during the disconnectedCallback lifecycle. */ onConnected(callback: () => void | (() => void)): void; /** * Helper function which will queue a function to be run just before the component is * removed from the DOM. This occurs during the disconnectedCallback lifecycle. */ onDisconnected(callback: () => void): void; /** * Returns the default context of the highest (ie. closest to the document root) ancestor component * that has configured a default context for the context name, * or it will return the component's own default context if no ancestor context was found. */ getContext<ContextKey extends keyof ContextRegistryT>(contextName: ContextKey): ContextRegistryT[ContextKey]; }
the_stack
import { Color } from 'three' import { calcArcPoint, parseNestedAtoms } from './measurement-representation' import StructureRepresentation, { StructureRepresentationParameters } from './structure-representation' import { RepresentationRegistry } from '../globals' import { Structure } from '../ngl' import { defaults } from '../utils' import { BufferData } from '../buffer/buffer' import MeshBuffer from '../buffer/mesh-buffer' import WideLineBuffer, { WideLineBufferData } from '../buffer/wideline-buffer' import { copyArray, uniformArray3, arraySum } from '../math/array-utils' import { v3add, v3cross, v3dot, v3multiplyScalar, v3fromArray, v3negate, v3new, v3normalize, v3sub, v3toArray, v3length } from '../math/vector-utils' import StructureView from '../structure/structure-view' import Viewer from '../viewer/viewer' const pointLength = 3 // One Point Length (number of coordinates of one point in 3D) const pointsInTriangle = 3 type ColorDefinition = Color | string | number | undefined interface HistogramColorParameters { histogramBinBorderColor: ColorDefinition adjacentBondArrowColor: ColorDefinition distantBondArrowColor: ColorDefinition frontHistogramColor: ColorDefinition backHistogramColor: ColorDefinition opaqueMiddleDiscColor: ColorDefinition } interface HistogramInputData extends Partial<HistogramColorParameters> { atomQuad: (number | string)[] histogram360: number[] } interface HistogramData extends HistogramInputData { atomPositions: Float32Array histogram360Scaled: number[] } interface WideLineData { startPoints: Float32Array endPoints: Float32Array startColors: Float32Array endColors: Float32Array } interface MeshData { triangles: Float32Array triangleColors: Float32Array } function createUpdatedObject(o: Object, updateSource: Object) { function hasKey<O>(obj: O, key: keyof any): key is keyof O { return key in obj } const result = { ...o } // Shallow copy for (const key in result) { if (hasKey(result, key) && hasKey(updateSource, key)) { result[key] = defaults(updateSource[key], result[key]) } } return result } function createColorArray(color: ColorDefinition, arrayLength: number) { const colorValue = new Color(color) const targetArray = new Float32Array(arrayLength * 3) uniformArray3(arrayLength, colorValue.r, colorValue.g, colorValue.b, targetArray) return targetArray } /** * @typedef {Object} DihedralHistogramRepresentationParameters - dihedral representation parameters * @mixes RepresentationParameters * @mixes StructureRepresentationParameters * * @property {HistogramInputData[]} histogramsData * List of HistogramInputData objects, which properties specifies each particular * histogram, and can contain particular histogram-specific parameters. * Obligatory properties are: * atomQuad - Quadruplet of selection strings or atom indices * histogram360 - List of values, representing histogram from 0 to 360 degrees. * @property {Boolean} histogramBinBorderVisible - Display the lines that separate circular histogram bins * @property {Boolean} scaleBinToSectorArea - Should sector-based histogram bins' * area be proportional to the bins' value */ export interface DihedralHistogramRepresentationParameters extends StructureRepresentationParameters { histogramsData: HistogramInputData[] histogramBinBorderVisible: boolean scaleBinToSectorArea: boolean } /** * Dihedral Histogram representation object * * Reperesentation consists of several parts: * opaqueMiddleDisc - opaque disc in the middle of the dihedral between front and back histograms * frontHistogram - circular histogram from the adjacent bond viewpoint * backHistogram - circular histogram from the distant bond viewpoint * histogramBinBorder - lines, which separate histogram bins * bondArrows - lines, which show the actual angle on the histogram disc * * @param {Structure} structure - the structure to measure angles in * @param {Viewer} viewer - a viewer object * @param {DihedralHistogramRepresentationParameters} params - Dihedral histogram representation parameters */ class DihedralHistogramRepresentation extends StructureRepresentation { protected histogramsData: HistogramData[] protected histogramBinBorderVisible: boolean protected histogramBinBorderWidth: number protected histogramBinBorderColor: ColorDefinition protected histogramBinBorderOpacity: number protected bondArrowVisible: boolean protected bondArrowWidth: number protected bondArrowOpacity: number protected adjacentBondArrowColor: ColorDefinition protected distantBondArrowColor: ColorDefinition protected histogramOpacity: number protected frontHistogramColor: ColorDefinition protected backHistogramColor: ColorDefinition protected opaqueMiddleDiscVisible: boolean protected opaqueMiddleDiscColor: ColorDefinition protected opaqueMiddleDiscOpacity: number protected scaleBinToSectorArea: boolean constructor(structure: Structure, viewer: Viewer, params: DihedralHistogramRepresentationParameters) { super(structure, viewer, params) this.type = 'dihedral-histogram' this.parameters = Object.assign({ histogramsData: { type: 'hidden', rebuild: true }, histogramBinBorderVisible: { type: 'boolean', default: true }, scaleBinToSectorArea: { type: 'boolean', rebuild: true, default: false } }, this.parameters) this.init(params) } init(params: Partial<DihedralHistogramRepresentationParameters>) { const p = params || {} const defaultColorData = { histogramBinBorderColor: 'grey', adjacentBondArrowColor: 'black', distantBondArrowColor: 'magenta', frontHistogramColor: 'green', backHistogramColor: 'blue', opaqueMiddleDiscColor: 'white' } const colorData = createUpdatedObject(defaultColorData, p) Object.assign(this, colorData) const defaultParameters = { histogramsData: [], histogramOpacity: 1.0, opaqueMiddleDiscVisible: true, opaqueMiddleDiscOpacity: 1.0, histogramBinBorderVisible: true, histogramBinBorderWidth: 1, histogramBinBorderOpacity: 0.5, bondArrowVisible: true, bondArrowWidth: 2, bondArrowOpacity: 1.0, scaleBinToSectorArea: false, } const parameters = createUpdatedObject(defaultParameters, p) Object.assign(this, parameters) this.histogramsData.forEach(x => { const specificColorData = createUpdatedObject(colorData, x) Object.assign(x, specificColorData) }) p.side = defaults(p.side, 'double') p.opacity = defaults(p.opacity, 0.5) p.radiusType = defaults(p.radiusType, 'size') p.radiusSize = defaults(p.radiusSize, 0.15) super.init(p) } getHistogramBinBorderBufferParameters() { return this.getBufferParams({ linewidth: this.histogramBinBorderWidth, visible: this.histogramBinBorderVisible, opacity: this.histogramBinBorderOpacity, }) } getBondArrowsBufferParameters() { return this.getBufferParams({ linewidth: this.bondArrowWidth, visible: this.bondArrowVisible, opacity: this.bondArrowOpacity, }) } getOpaqueMiddleDiscBufferParameters() { return this.getBufferParams({ visible: this.opaqueMiddleDiscVisible, opacity: this.opaqueMiddleDiscOpacity }) } getHistogramBufferParameters() { return this.getBufferParams({ visible: true, opacity: this.histogramOpacity, side: "double" }) } createData(sview: StructureView) { if (!sview.atomCount || !this.histogramsData.length) return this.histogramsData.forEach(x => x.atomPositions = parseNestedAtoms(sview, [x.atomQuad])) const scaleData = this.scaleBinToSectorArea ? function (y: number) { return Math.sqrt(y) } : function (y: number) { return y } this.histogramsData.forEach(x => x.histogram360Scaled = x.histogram360.map(scaleData)) function Float32Concat(arrays: Float32Array[]) { const lengths = arrays.map(x => x.length) const result = new Float32Array(arraySum(lengths)) let accumulatedOffset = 0 for (let i = 0; i < arrays.length; i++) { result.set(arrays[i], accumulatedOffset) accumulatedOffset += arrays[i].length } return result } function createWideLineBuffer(linesList: WideLineData[], params: {}) { return new WideLineBuffer( { position1: Float32Concat(linesList.map(x => x.startPoints)), position2: Float32Concat(linesList.map(x => x.endPoints)), color: Float32Concat(linesList.map(x => x.startColors)), color2: Float32Concat(linesList.map(x => x.endColors)), } as WideLineBufferData, params) } function createMeshBuffer(mesh: MeshData[], params: {}) { return new MeshBuffer( { position: Float32Concat(mesh.map(x => x.triangles)), color: Float32Concat(mesh.map(x => x.triangleColors)) } as BufferData, params) } const dihedralDataArray = [] for (let i = 0; i < this.histogramsData.length; i++) { let dihedralData = undefined let currentHistogramData = this.histogramsData[i] let currentHistogram360 = currentHistogramData.histogram360 if (currentHistogram360.length >= 3) { dihedralData = calculateDihedralHistogram(currentHistogramData) } if (typeof dihedralData === "undefined") continue dihedralDataArray.push(dihedralData) } this.frontHistogramBinBordersBuffer = createWideLineBuffer( dihedralDataArray.map(x => x.frontHistogramBinBorders), this.getHistogramBinBorderBufferParameters() ) this.backHistogramBinBordersBuffer = createWideLineBuffer( dihedralDataArray.map(x => x.backHistogramBinBorders), this.getHistogramBinBorderBufferParameters() ) this.adjacentBondArrowsBuffer = createWideLineBuffer( dihedralDataArray.map(x => x.adjacentBondArrows), this.getBondArrowsBufferParameters() ) this.distantBondArrowsBuffer = createWideLineBuffer( dihedralDataArray.map(x => x.distantBondArrows), this.getBondArrowsBufferParameters() ) this.opaqueMiddleDiscBuffer = createMeshBuffer( dihedralDataArray.map(x => x.opaqueMiddleDisc), this.getOpaqueMiddleDiscBufferParameters() ) this.frontHistogramBuffer = createMeshBuffer( dihedralDataArray.map(x => x.frontHistogram), this.getHistogramBufferParameters() ) this.backHistogramBuffer = createMeshBuffer( dihedralDataArray.map(x => x.backHistogram), this.getHistogramBufferParameters() ) return { bufferList: [].concat( this.frontHistogramBinBordersBuffer, this.backHistogramBinBordersBuffer, this.adjacentBondArrowsBuffer, this.distantBondArrowsBuffer, this.opaqueMiddleDiscBuffer, this.frontHistogramBuffer, this.backHistogramBuffer ) } } setParameters(params: Partial<DihedralHistogramRepresentationParameters>) { const rebuild = false const what = {} super.setParameters(params, what, rebuild) if (params && (params.histogramBinBorderVisible !== undefined)) { this.setVisibility(this.visible) } return this } setVisibility(value: boolean, noRenderRequest?: boolean) { super.setVisibility(value, true) if (this.frontHistogramBinBordersBuffer) { this.frontHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible) } if (this.backHistogramBinBordersBuffer) { this.backHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible) } if (!noRenderRequest) this.viewer.requestRender() return this } } /** * Calculates the data required to create {Buffer} objects for one histogram, given positions * @param Float32Array positionOfDihedralAtoms 3*4 array of coordinates * @param NumberArray histogram array of coordinates * @return Arrays for building buffers */ function calculateDihedralHistogram(histogramData: HistogramData) { const positionOfDihedralAtoms = histogramData.atomPositions const histogram = histogramData.histogram360Scaled; const totalSectorTrianglesInOpaqueMiddleDisc = histogram.length <= 180 ? 360 : histogram.length * 2 const frontAndBack = 2 const opaqueMiddleDisc = { triangles: new Float32Array(totalSectorTrianglesInOpaqueMiddleDisc * pointsInTriangle * pointLength), triangleColors: createColorArray(histogramData.opaqueMiddleDiscColor, totalSectorTrianglesInOpaqueMiddleDisc * pointsInTriangle) } const frontHistogram = { triangles: new Float32Array(histogram.length * pointsInTriangle * pointLength), triangleColors: createColorArray(histogramData.frontHistogramColor, histogram.length * pointsInTriangle) } const backHistogram = { triangles: new Float32Array(histogram.length * pointsInTriangle * pointLength), triangleColors: createColorArray(histogramData.backHistogramColor, histogram.length * pointsInTriangle) } const frontHistogramBinBorders = { startPoints: new Float32Array(histogram.length * pointLength), endPoints: new Float32Array(histogram.length * pointLength), startColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length), endColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length) } const backHistogramBinBorders = { startPoints: new Float32Array(histogram.length * pointLength), endPoints: new Float32Array(histogram.length * pointLength), startColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length), endColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length) } const adjacentBondArrows = { startPoints: new Float32Array(frontAndBack * pointLength), endPoints: new Float32Array(frontAndBack * pointLength), startColors: createColorArray(histogramData.adjacentBondArrowColor, histogram.length), endColors: createColorArray(histogramData.adjacentBondArrowColor, histogram.length) } const distantBondArrows = { startPoints: new Float32Array(frontAndBack * pointLength), endPoints: new Float32Array(frontAndBack * pointLength), startColors: createColorArray(histogramData.distantBondArrowColor, histogram.length), endColors: createColorArray(histogramData.distantBondArrowColor, histogram.length) } const p1 = v3new() const p2 = v3new() const p3 = v3new() const p4 = v3new() const v21 = v3new() const v23 = v3new() const v32 = v3new() const v34 = v3new() const mid = v3new() const inPlane1 = v3new() const inPlane2 = v3new() const cross1 = v3new() const cross2 = v3new() const arcPoint = v3new() const tmp = v3new() const tmp2 = v3new() // Set Atom Coordinates const dihedralAtomVectors = [p1, p2, p3, p4] for (let i = 0; i < dihedralAtomVectors.length; i++) { v3fromArray(dihedralAtomVectors[i], positionOfDihedralAtoms, i * pointLength) } // Vectors between points v3sub(v21, p1, p2) v3sub(v23, p3, p2) v3sub(v34, p4, p3) if (v3length(v23) === 0.0) { return // Can't define axis } v3multiplyScalar(tmp, v23, 0.5) v3add(mid, p2, tmp) v3normalize(v21, v21) v3normalize(v23, v23) v3normalize(v34, v34) v3negate(v32, v23) // Calculate vectors perp to v23 (lying in plane (1,2,3) and (2,3,4)) v3multiplyScalar(tmp, v32, v3dot(v32, v21)) v3sub(inPlane1, v21, tmp) v3multiplyScalar(tmp, v23, v3dot(v23, v34)) v3sub(inPlane2, v34, tmp) if (v3length(inPlane1) === 0.0 || v3length(inPlane2) === 0.0) { return // Indeterminate angle } v3normalize(inPlane1, inPlane1) v3normalize(inPlane2, inPlane2) // Can use acos as normalized and non-zero const absAngle = Math.acos(v3dot(inPlane1, inPlane2)) v3cross(cross1, v32, inPlane1) v3cross(cross2, v23, inPlane2) v3normalize(cross1, cross1) v3normalize(cross2, cross2) let angle = absAngle if (v3dot(cross1, inPlane2) < 0.0) { angle = -absAngle } v3add(arcPoint, mid, inPlane1) // Calculate necessary constants const maxHist = Math.max.apply(null, histogram) const histBinAngleStep = (Math.PI * 2) / histogram.length function setHistogramBinCoordinates(out: Float32Array, ind: number, zeroDegreeVector: Float32Array, crossVector: Float32Array, histBinAngleStep: number) { const startOffset = ind * pointsInTriangle * pointLength v3toArray(mid, out, startOffset) const scalingFactor = Number(histogram[ind]) / maxHist v3multiplyScalar(tmp, zeroDegreeVector, scalingFactor) v3multiplyScalar(tmp2, crossVector, scalingFactor) calcArcPoint(arcPoint, mid, tmp, tmp2, ind * histBinAngleStep) v3toArray(arcPoint, out, startOffset + 1 * pointLength) calcArcPoint(arcPoint, mid, tmp, tmp2, (ind + 1) * histBinAngleStep) v3toArray(arcPoint, out, startOffset + 2 * pointLength) } function setOneSideHistogram(discHistogram: MeshData, binBorders: { startPoints: Float32Array, endPoints: Float32Array }, ind: number, zeroDegreeVector: Float32Array, crossVector: Float32Array) { // Set Bond Arrows copyArray(mid, adjacentBondArrows.startPoints, 0, ind * pointLength, mid.length) calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, 0 + histBinAngleStep * 0) copyArray(tmp, adjacentBondArrows.endPoints, 0, ind * pointLength, mid.length) copyArray(mid, distantBondArrows.startPoints, 0, ind * pointLength, mid.length) calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, angle) copyArray(tmp, distantBondArrows.endPoints, 0, ind * pointLength, mid.length) // Set Histogram Bin Borders for (let i = 0; i < histogram.length; i++) { copyArray(mid, binBorders.startPoints, 0, i * 3, mid.length) calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, 0 + histBinAngleStep * i) copyArray(tmp, binBorders.endPoints, 0, i * 3, tmp.length) } // Set Histogram Bins for (let sectionIndex = 0; sectionIndex < histogram.length; sectionIndex++) { setHistogramBinCoordinates(discHistogram.triangles, sectionIndex, zeroDegreeVector, crossVector, histBinAngleStep) } } // Opaque disc const opaqueCircleSectorAngleStep = Math.PI * 2 / totalSectorTrianglesInOpaqueMiddleDisc for (let sectionIndex = 0; sectionIndex < totalSectorTrianglesInOpaqueMiddleDisc; sectionIndex++) { const startOffset = sectionIndex * pointsInTriangle * pointLength v3toArray(mid, opaqueMiddleDisc.triangles, startOffset) calcArcPoint(arcPoint, mid, inPlane1, cross1, sectionIndex * opaqueCircleSectorAngleStep) v3toArray(arcPoint, opaqueMiddleDisc.triangles, startOffset + 1 * pointLength) calcArcPoint(arcPoint, mid, inPlane1, cross1, (sectionIndex + 1) * opaqueCircleSectorAngleStep) v3toArray(arcPoint, opaqueMiddleDisc.triangles, startOffset + 2 * pointLength) } // Front Histogram const distanceToOpaqueDisc = 0.01 v3multiplyScalar(tmp, v23, -distanceToOpaqueDisc) // Get a vector to move "mid" just a bit from opaque disc v3add(mid, mid, tmp) setOneSideHistogram(frontHistogram, frontHistogramBinBorders, 0, inPlane1, cross1) // Back Histogram v3multiplyScalar(tmp, v23, 2 * distanceToOpaqueDisc) // Get a vector to move "mid" back and plus just a bit from opaque disc the other way v3add(mid, mid, tmp) setOneSideHistogram(backHistogram, backHistogramBinBorders, 1, inPlane2, cross2) return { opaqueMiddleDisc, frontHistogram, backHistogram, frontHistogramBinBorders, backHistogramBinBorders, adjacentBondArrows, distantBondArrows } } RepresentationRegistry.add('dihedral-histogram', DihedralHistogramRepresentation) export default DihedralHistogramRepresentation
the_stack
import { fromU32, toCharCodes } from "../utils/string"; import { copyRange } from "../utils/arrays"; import { $$hex } from "../utils/debug"; import { RGBA5551toRGBA32 } from "../utils/img/RGBA5551"; import { BMPtoRGBA } from "../utils/img/BMP"; type IFormObjType = "FORM" | "HBINMODE" | "OBJ1" | "COL1" | "MAT1" | "ATR1" | "VTX1" | "FAC1" | "MTN1" | "BMP1" | "PAL1" | "SKL1" | "STRG" | "MAP1"; type IFormObjDict = { [key in IFormObjType]: IFormObjEntry[] }; export interface IFormObj extends IFormObjDict { entries: IFormObjType[]; } interface IFormObjEntry { raw: ArrayBuffer; parsed?: any; } export interface IFAC1VertexEntry { vertexIndex: number; materialIndex: number; u: number; v: number; } export interface IFAC1Parsed { materialIndex: number; atrIndex: number; mystery3: number; vtxEntries: IFAC1VertexEntry[]; } export interface IVTXParsed { vertices: IVTX1Vertex[]; scale: number; } export interface IVTX1Vertex { x: number; y: number; z: number; normalX: number; normalY: number; normalZ: number; } interface ISLK1Parsed { globalIndex: number; skls: any[]; } interface IPAL1Parsed { bpp: number; globalIndex: number; colors: number[]; } // Extracts a FORM file into a usable format. export const FORM = class FORM { static unpack(formView: ArrayBuffer | DataView): IFormObj | null { if (!(formView instanceof DataView)) formView = new DataView(formView); if (!FORM.isForm(formView)) return null; let formObj = Object.create(null); formObj.entries = []; let curOffset = 8; while (curOffset < formView.byteLength - 2) { // Roughly-ish the end let type: string | number = formView.getUint32(curOffset); type = fromU32(type); if (type === "HBIN") { curOffset += 4; type += fromU32(formView.getUint32(curOffset)); // "MODE" } formObj.entries.push(type); curOffset += 4; let len = formView.getUint32(curOffset); curOffset += 4; let entry: IFormObjEntry = { raw: formView.buffer.slice(curOffset, curOffset + len) }; let parsed = FORM.parseType(type as IFormObjType, entry.raw); if (parsed) entry.parsed = parsed; formObj[type] = formObj[type] || []; formObj[type].push(entry); curOffset += len + (len % 2); } // With all BMPs and PALs parsed, now we can decode the BMPs. if (formObj.BMP1) { for (let i = 0; i < formObj.BMP1.length; i++) { let bmpEntry = formObj.BMP1[i]; bmpEntry.parsed = FORM.parseBMP(bmpEntry.raw, formObj.PAL1); } } return formObj; } static pack(formObj: IFormObj): ArrayBuffer { let formBuffer = new ArrayBuffer(FORM.getByteLength(formObj)); let formView = new DataView(formBuffer); formView.setUint32(0, 0x464F524D); // "FORM" formView.setUint32(4, formBuffer.byteLength - 8); // Don't count the "FORM____" at the top. let entryWriteState: { [type in IFormObjType]?: number } = {}; let curIndex = 8; for (let i = 0; i < formObj.entries.length; i++) { let entryType = formObj.entries[i]; let entryNum = entryWriteState[entryType] || 0; entryWriteState[entryType] = entryNum + 1; // Write the type name. let typeBytes = toCharCodes(entryType); for (let b = 0; b < typeBytes.length; b++) { formView.setUint8(curIndex, typeBytes[b]); curIndex++; } let entry = formObj[entryType][entryNum]; // Write the entry length. let entrySize = entry.raw.byteLength; formView.setUint32(curIndex, entrySize); curIndex += 4; // Copy in the actual data. copyRange(formView, entry.raw, curIndex, 0, entrySize); curIndex += entrySize + (entrySize % 2); } return formBuffer; } static isForm(viewOrBuffer: ArrayBuffer | DataView) { if (!viewOrBuffer) return false; if (!(viewOrBuffer instanceof DataView)) viewOrBuffer = new DataView(viewOrBuffer); return viewOrBuffer.getUint32(0) === 0x464F524D; // "FORM" } static getByteLength(formObj: IFormObj) { let byteLen = 0; for (let type in formObj) { if (type === "entries") continue; for (let i = 0; i < (formObj as any)[type].length; i++) { let rawLen = (formObj as any)[type][i].raw.byteLength; // The raw data + rounded up to 16-bit boundary + the TYPE text + entry length value. byteLen += rawLen + (rawLen % 2) + type.length + 4; } } return byteLen + 8; // Add the "FORM____" at the beginning. } static parseType(type: IFormObjType, raw: ArrayBuffer) { switch (type) { case "HBINMODE": return FORM.parseHBINMODE(raw); case "OBJ1": return FORM.parseOBJ1(raw); case "COL1": return FORM.parseCOL1(raw); case "MAT1": return FORM.parseMAT1(raw); case "ATR1": return FORM.parseATR1(raw); case "VTX1": return FORM.parseVTX1(raw); case "FAC1": return FORM.parseFAC1(raw); case "PAL1": return FORM.parsePAL1(raw); case "SKL1": return FORM.parseSKL1(raw); case "STRG": return FORM.parseSTRG(raw); } return null; } static parseHBINMODE(raw: ArrayBuffer) { let rawView = new DataView(raw); const result = { E: rawView.getUint8(0x14), F: rawView.getUint8(0x15), G: rawView.getUint8(0x16), }; if (result.E !== 0x45 || result.F !== 0x46 || result.G !== 0x47) { console.warn("HBINMODE unexpected EFG => ", result); // Corresponds to ZYX rotation? } return result; } static parseOBJ1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: any = { objects: [], mystery1: rawView.getUint16(2), }; let objCount = rawView.getUint16(0); let objectOffset = 4; for (let i = 0; i < objCount; i++) { let objSize = rawView.getUint16(objectOffset); let objType = rawView.getUint8(objectOffset + 2); let globalIndex = rawView.getUint16(objectOffset + 3); objectOffset += 5; let obj: any; switch (objType) { case 0x3D: obj = { children: [], }; const subObjCount = rawView.getUint16(objectOffset); for (let j = 0; j < subObjCount; j++) { obj.children.push(rawView.getUint16(objectOffset + 2 + (2 * j))); } Object.assign(obj, FORM._parseOBJ1Transforms(rawView, objectOffset + 2 + (2 * subObjCount))); break; case 0x3A: obj = { mystery1: rawView.getUint8(objectOffset), faceIndex: rawView.getUint16(objectOffset + 1), faceCount: rawView.getUint16(objectOffset + 3), }; Object.assign(obj, FORM._parseOBJ1Transforms(rawView, objectOffset + 5)); break; case 0x10: // Points to skeleton entry // 9/11 mp1 obj = { skeletonGlobalIndex: rawView.getUint16(objectOffset), }; Object.assign(obj, FORM._parseOBJ1Transforms(rawView, objectOffset + 2)); break; case 0x3B: // TODO mp3 25/2 obj = {}; console.warn("Object type 0x3B"); break; case 0x3E: // TODO obj = {}; //console.warn("Object type 0x3E"); break; case 0x61: // TODO this is common, don't know what it is, just has transform obj = {}; Object.assign(obj, FORM._parseOBJ1Transforms(rawView, objectOffset)); break; case 0x5D: // TODO mp3 13/0 // Refers to objects of type 0x61 obj = {}; console.warn("Object type 0x5D"); break; default: console.warn(`Unrecognized object type ${$$hex(objType)}`); obj = {}; break; } obj.objType = objType; obj.globalIndex = globalIndex; result.objects.push(obj); objectOffset += objSize - 3; // -3 because +5 above included 3 from objSize } return result; } static _parseOBJ1Transforms(rawView: DataView, offset: number) { return { posX: rawView.getFloat32(offset), posY: rawView.getFloat32(offset + 4), posZ: rawView.getFloat32(offset + 8), rotX: rawView.getFloat32(offset + 12), rotY: rawView.getFloat32(offset + 16), rotZ: rawView.getFloat32(offset + 20), scaleX: rawView.getFloat32(offset + 24), scaleY: rawView.getFloat32(offset + 28), scaleZ: rawView.getFloat32(offset + 32), }; } static parseCOL1(raw: ArrayBuffer) { let rawView = new DataView(raw); let colors = []; let colorCount = rawView.getUint16(0); let colorOffset = 2; for (let i = 0; i < colorCount; i++) { colors.push(rawView.getUint32(colorOffset)); colorOffset += 4; } return colors; } static parseMAT1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: { materials: any[] } = { materials: [], }; let materialCount = rawView.getUint16(0); let materialOffset = 2; for (let i = 0; i < materialCount; i++) { let material = { mystery1: rawView.getUint16(materialOffset), colorIndex: rawView.getUint16(materialOffset + 2), mystery3: rawView.getUint16(materialOffset + 4), mystery4: rawView.getFloat32(materialOffset + 6), mystery5: rawView.getUint16(materialOffset + 10), }; result.materials.push(material); materialOffset += 12; } return result; } static parseATR1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: { atrs: any[] } = { atrs: [], }; let atrCount = rawView.getUint16(0); let atrOffset = 2; for (let i = 0; i < atrCount; i++) { let atr = { size: rawView.getUint16(atrOffset), // 2A // FF FF xBehavior: rawView.getUint8(atrOffset + 0x5), yBehavior: rawView.getUint8(atrOffset + 0x6), // 2F 2F 01 bmpGlobalIndex: rawView.getUint16(atrOffset + 0xA), }; result.atrs.push(atr); atrOffset += atr.size + 2; } return result; } static parseVTX1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: IVTXParsed = { vertices: [], scale: rawView.getFloat32(4), }; let vertexCount = rawView.getUint16(0); let vertexOffset = 8; for (let i = 0; i < vertexCount; i++) { let vertex = { x: rawView.getInt16(vertexOffset), y: rawView.getInt16(vertexOffset + 2), z: rawView.getInt16(vertexOffset + 4), normalX: rawView.getInt8(vertexOffset + 6), normalY: rawView.getInt8(vertexOffset + 7), normalZ: rawView.getInt8(vertexOffset + 8), }; result.vertices.push(vertex); vertexOffset += 9; } return result; } static parseFAC1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: any = { faces: [], }; let faceCount = rawView.getUint16(0); let faceOffset = 8; for (let i = 0; i < faceCount; i++) { let faceType = rawView.getUint8(faceOffset); if (faceType !== 0x35 && faceType !== 0x16 && faceType !== 0x30) // 0x30 in mainfs 9/81 mp1 throw new Error(`Unrecognized faceType in FAC1: ${$$hex(faceType)}`); let face: IFAC1Parsed = { vtxEntries: [], } as any; result.faces.push(face); faceOffset += 1; // Start after face_type if (faceType === 0x30) { console.warn("Unsupported face type 0x30"); faceOffset += 6; // TODO: What is 0x30 type? VTX num VTX? } else { const vtxEntryCount = faceType === 0x35 ? 4 : 3; for (let j = 0; j < vtxEntryCount; j++) { face.vtxEntries[j] = { vertexIndex: rawView.getUint16(faceOffset), materialIndex: rawView.getInt16(faceOffset + 2), u: rawView.getFloat32(faceOffset + 4), v: rawView.getFloat32(faceOffset + 8), }; faceOffset += 12; // sizeof(FAC1VtxEntry) } } face.materialIndex = rawView.getInt16(faceOffset); face.atrIndex = rawView.getInt16(faceOffset + 2); face.mystery3 = rawView.getUint8(faceOffset + 4); // 0x36 // TODO 0x38 in mp2 31/5 //if (face.mystery3 !== 0x36 && face.mystery3 !== 0x37 && face.mystery3 !== 0x38 && face.mystery3 !== 0x30) // throw new Error(`Unexpected mystery3 in FAC1 ${$$hex(face.mystery3)}`); // mp3 81/2 flip x, 0x37 ? if (face.mystery3 !== 0x36) console.warn("Unsupported FAC1 mystery3 ", $$hex(face.mystery3)); faceOffset += 5; } return result; } static parsePAL1(raw: ArrayBuffer) { let rawView = new DataView(raw); let result: IPAL1Parsed = { colors: [], bpp: 0, globalIndex: rawView.getUint16(0), }; let colorCount = rawView.getUint16(2); result.bpp = Math.floor((raw.byteLength - 4) / colorCount) * 8; let colorOffset = 4; for (let i = 0; i < colorCount; i++) { if (result.bpp === 32) result.colors.push(rawView.getUint32(colorOffset)); else if (result.bpp === 16) result.colors.push(rawView.getUint16(colorOffset)); else if (result.bpp === 8) result.colors.push(rawView.getUint8(colorOffset)); else throw new Error(`FORM.parseType(PAL1): bpp: ${result.bpp}`); colorOffset += result.bpp / 8; } return result; } static parseSKL1(raw: ArrayBuffer) { const rawView = new DataView(raw); const sklCount = rawView.getUint8(2); const result: ISLK1Parsed = { globalIndex: rawView.getUint16(0), skls: [], }; let sklOffset = 3; for (let i = 0; i < sklCount; i++) { const skl = { mystery1: rawView.getUint8(sklOffset), objGlobalIndex: rawView.getUint16(sklOffset + 1), nextSiblingRelativeIndex: rawView.getUint16(sklOffset + 0x33), isParentNode: rawView.getUint16(sklOffset + 0x35), mystery2: rawView.getUint8(sklOffset + 0x36), }; Object.assign(skl, FORM._parseOBJ1Transforms(rawView, sklOffset + 3)); result.skls.push(skl); sklOffset += 56; // sizeof(SKL1Entry) } return result; } static parseSTRG(raw: ArrayBuffer) { let rawView = new DataView(raw); let strings = []; let strCount = rawView.getUint16(0); let strOffset = 2 + strCount; for (let i = 0; i < strCount; i++) { let str = ""; let strLen = rawView.getUint8(2 + i); for (let j = 0; j < strLen; j++) { str += String.fromCharCode(rawView.getUint8(strOffset + j)); } strOffset += strLen; strings.push(str); } return strings; } static parseBMP(raw: ArrayBuffer, PAL1: any) { const rawView = new DataView(raw); const format = rawView.getUint16(0x2); const width = rawView.getUint16(0x05); const height = rawView.getUint16(0x07); if (format === 0x128 || format === 0x228) { // Traditional bitmap format // 0x128 is just a bitmap // 0x228 starts out the same, but TODO it also has some sort of extra RGBA data appended. // mp1 0/93, 0/94, 0/95, 46/2, 48/15, 54/5, 57/3 if (!PAL1) throw new Error(`Palette needed for BMP format ${$$hex(format)}`); const paletteGlobalIndex = rawView.getUint16(0x09); const inBmpSize = rawView.getUint16(0x0F); // Find associated palette by global index let palette; for (let i = 0; i < PAL1.length; i++) { if (PAL1[i].parsed.globalIndex === paletteGlobalIndex) { palette = PAL1[i].parsed; break; } } if (!palette) { throw new Error(`Could not locate palette at global index ${paletteGlobalIndex}`); } // Doesn't appear to indicate BPP, but we can calculate from size and dimens. const inBpp = 8 / ((width * height) / inBmpSize); const outBpp = palette.bpp; const inBmpData = new DataView(raw, 0x11, inBmpSize); return { globalIndex: rawView.getUint16(0), origFormat: format, paletteGlobalIndex, width, height, src: BMPtoRGBA(inBmpData, palette.colors, inBpp, outBpp), }; } else if (format === 0x127) { // mp1 9/138 // Just raw RGBA already const bpp = rawView.getUint8(0x4); const imageByteLength = rawView.getUint16(0xB); switch (bpp) { case 16: return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: RGBA5551toRGBA32(raw.slice(0xD, 0xD + imageByteLength), width, height), }; case 32: return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: raw.slice(0xD, 0xD + imageByteLength), }; default: console.warn(`BMP1 0x127 had unsupported bpp ${bpp}`); } } else if (format === 0x126) { // 0x126 mp1 9/25 // 24 bits per color // TODO: Are the bits right, or is there alpha? const imageByteLength = rawView.getUint16(0xB); const outBuffer = new ArrayBuffer(width * height * 4); const outView = new DataView(outBuffer); for (let i = 0; i < (imageByteLength / 3); i++) { const inByte1 = rawView.getUint8(0xD + i); const inByte2 = rawView.getUint8(0xD + i + 1); const inByte3 = rawView.getUint8(0xD + i + 2); const rgba32 = (inByte1 << 24) | (inByte2 << 16) | (inByte3 << 8) | 0xFF; const outIndex = i * 4; outView.setUint32(outIndex, rgba32); } return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: outBuffer, }; } else if (format === 0x125) { // Grayscale? // TODO: I don't think this is right? Some sort of shadow mask? const imageByteLength = rawView.getUint16(0xB); const outBuffer = new ArrayBuffer(imageByteLength * 4); const outView = new DataView(outBuffer); for (let i = 0; i < imageByteLength; i++) { const inByte = rawView.getUint8(0xD + i); const alpha = (inByte & 0x0F) | ((inByte & 0x0F) << 4); const grayscale = (inByte & 0xF0) | ((inByte & 0xF0) >>> 4); const rgba32 = (grayscale << 24) | (grayscale << 16) | (grayscale << 8) | alpha; const outIndex = i * 4; outView.setUint32(outIndex, rgba32); } return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: outBuffer, }; } else if (format === 0x124) { // 0x124 mp3 11/51 // Grayscale? // TODO: I don't think this is right? Some sort of shadow mask? const imageByteLength = rawView.getUint16(0xB); const outBuffer = new ArrayBuffer(imageByteLength * 8); const outView = new DataView(outBuffer); let outLoc = 0; for (let i = 0; i < imageByteLength; i++) { const inByte = rawView.getUint8(0xD + i); let out1byte = (inByte & 0xF0) >>> 4; out1byte |= (inByte & 0xF0); outView.setUint32(outLoc, (out1byte << 24) | (out1byte << 16) | (out1byte << 8) | 0xFF); outLoc += 4; let out2byte = (inByte & 0x0F); out2byte |= (out2byte << 4); outView.setUint32(outLoc, (out2byte << 24) | (out2byte << 16) | (out2byte << 8) | 0xFF); outLoc += 4; } return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: outBuffer, }; } // TODO: Other formats console.warn(`Could not parse BMP format ${$$hex(format)}`); return { globalIndex: rawView.getUint16(0), origFormat: format, width, height, src: new ArrayBuffer(width * height * 4), }; } static replaceBMP(formObj: IFormObj, bmpIndex: number, buffer: ArrayBuffer, palette: any) { // FIXME?: For now, this assumes that the new BMP has the same properties basically. // Also look at the huge blob at the bottom LOL get this thing done! // Just write over the bitmap data directly. copyRange(formObj.BMP1[bmpIndex].raw, buffer, 0x11, 0, buffer.byteLength); // Write the palette, which needs some care. formObj.PAL1[bmpIndex].parsed = palette; let oldPalGlobalIndex = (new DataView(formObj.PAL1[bmpIndex].raw)).getUint16(0); let newRaw = formObj.PAL1[bmpIndex].raw = new ArrayBuffer(4 + (palette.colors.length * 4)); let newPaletteView = new DataView(newRaw); newPaletteView.setUint16(0, oldPalGlobalIndex); newPaletteView.setUint16(2, palette.colors.length); let curOutOffset = 4; for (let i = 0; i < palette.colors.length; i++) { newPaletteView.setUint32(curOutOffset, palette.colors[i]); curOutOffset += 4; } // TODO: This was another implementation: write raw RGBA with type 0x127. // But the board select wouldn't show up when I tried this. // const oldBmpView = new DataView(formObj.BMP1[bmpIndex].raw); // const oldGlobalIndex = oldBmpView.getUint16(0); // const newBmpEntry = new ArrayBuffer(buffer.byteLength + 0xD); // const bmpView = new DataView(newBmpEntry); // bmpView.setUint16(0, oldGlobalIndex); // bmpView.setUint16(0x2, 0x0127); // RGBA // bmpView.setUint8(0x4, 0x20); // 32-bit? // bmpView.setUint16(0x5, width); // bmpView.setUint16(0x7, height); // bmpView.setUint32(0x9, buffer.byteLength); // copyRange(bmpView, buffer, 0xD, 0, buffer.byteLength); // formObj.BMP1[bmpIndex].raw = newBmpEntry; // // Update the parsed BMP just to keep the obj state consistent. // formObj.BMP1[bmpIndex].parsed = FORM.parseBMP(newBmpEntry, null); } // Retrieves a value (or possibly multiple values) by global index. static getByGlobalIndex(form: IFormObj, section: IFormObjType, globalIndex: number) { if (!form[section]) return null; const values = []; for (var s = 0; s < form[section].length; s++) { const parsedValue = form[section][s].parsed; if (!parsedValue) throw new Error(`No parsed value for ${section}`); if (parsedValue.hasOwnProperty("globalIndex")) { if (parsedValue.globalIndex === globalIndex) values.push(parsedValue); } else { let arrToSearch = parsedValue; switch (section) { case "OBJ1": arrToSearch = parsedValue.objects; break; } for (let i = 0; i < arrToSearch.length; i++) { const val = arrToSearch[i]; if (!val.hasOwnProperty("globalIndex")) throw new Error(`globalIndex is not a property of the searched ${section} array in getByGlobalIndex`); if (val.globalIndex === globalIndex) values.push(val); } } } if (!values.length) return null; if (values.length === 1) return values[0]; return values; } static getObjectsByType(form: IFormObj, type: number) { const OBJs = form.OBJ1[0].parsed.objects; const objsOfType = []; for (let i = 0; i < OBJs.length; i++) { if (OBJs[i].objType === type) { objsOfType.push(OBJs[i]); } } return objsOfType; } }
the_stack
import {OpenYoloCredential, OpenYoloCredentialHintOptions, OpenYoloCredentialRequestOptions, OpenYoloProxyLoginResponse} from '../protocol/data'; import {RenderMode} from '../protocol/data'; import {OpenYoloErrorType, OpenYoloInternalError} from '../protocol/errors'; import {FeatureConfig} from '../protocol/feature_config'; import {PreloadRequest, PreloadRequestType} from '../protocol/preload_request'; import {SecureChannel} from '../protocol/secure_channel'; import {generateId, sha256, startTimeoutRacer, TimeoutRacer} from '../protocol/utils'; import {CancelLastOperationRequest} from './cancel_last_operation_request'; import {CredentialRequest} from './credential_request'; import {CredentialSave} from './credential_save'; import {DisableAutoSignIn} from './disable_auto_sign_in'; import {HintAvailableRequest} from './hint_available_request'; import {HintRequest} from './hint_request'; import {createNavigatorCredentialsApi} from './navigator_credentials'; import {ProviderFrameElement} from './provider_frame_elem'; import {ProxyLogin} from './proxy_login'; import {respondToHandshake} from './verify'; const MOBILE_USER_AGENT_REGEX = /android|iphone|ipod|iemobile/i; /** * Provides a mechanism for credential exchange between the current origin and * the user's credential provider (e.g. Smart Lock for Passwords). */ export interface OpenYoloApi { /** * Requests the credential provider whether hints are available or not for the * current user. * * @param options * Describes the types of credentials that are supported by the origin. * @return * A promise that resolves with true if at least one hint is available, * and resolves with false if none are available. The promise will not * reject: if an error happen, it should resolve with false. */ hintsAvailable(options: OpenYoloCredentialHintOptions): Promise<boolean>; /** * Attempts to retrieve a sign-up hint that can be used to create a new * user account. * * @param options * Describes the types of credentials that are supported by the origin, * and customization properties for the display of any UI pertaining to * releasing this credential. * @return * A promise for a credential hint. The promise will be rejected if the * user cancels the hint selection process. */ hint(options: OpenYoloCredentialHintOptions): Promise<OpenYoloCredential>; /** * Attempts to retrieve a credential for the current origin. * * @param options * Describes the types of credentials that are supported by the origin. * @return * A promise for the credential, which will be rejected if there are no * credentials available or the user refuses to release the credential. * Otherwise, the promise will resolve with a credential that the app * can use. */ retrieve(options: OpenYoloCredentialRequestOptions): Promise<OpenYoloCredential>; /** * Attempts to save the provided credential, which will update or create * a credential as necessary. * * @param credential * The credential to be stored. * @return * A promise for the completion of the operation. The promise will always * resolve, and does not indicate whether the credential was actually * saved. */ save(credential: OpenYoloCredential): Promise<void>; /** * Prevents the automatic release of a credential from the retrieve operation. * This should be invoked when the user signs out, in order to prevent an * automatic sign-in loop. * * @return * A promise for the completion of notifying the provider to disable * automatic sign-in. */ disableAutoSignIn(): Promise<void>; /** * Dispatches a credential to the origin's declared authentication system, * via the credential provider. * * This method *may* not be implemented for the launch if time does not permit * even if it would be better to have it in the first version. * * @param credential * The credential to be dispatched. * @return * A promise for the response data from the authentication system. */ proxyLogin(credential: OpenYoloCredential): Promise<OpenYoloProxyLoginResponse>; /** * Cancels the last pending OpenYOLO request. */ cancelLastOperation(): Promise<void>; } /** * A variant of the OpenYoloApi interface, with support for operation timeouts. */ export interface OpenYoloWithTimeoutApi { hintsAvailable( options: OpenYoloCredentialHintOptions, timeoutRacer: TimeoutRacer): Promise<boolean>; hint(options: OpenYoloCredentialHintOptions, timeoutRacer: TimeoutRacer): Promise<OpenYoloCredential>; retrieve( options: OpenYoloCredentialRequestOptions, timeoutRacer: TimeoutRacer): Promise<OpenYoloCredential>; save(credential: OpenYoloCredential, timeoutRacer: TimeoutRacer): Promise<void>; disableAutoSignIn(timeoutRacer: TimeoutRacer): Promise<void>; proxyLogin(credential: OpenYoloCredential, timeoutRacer: TimeoutRacer): Promise<OpenYoloProxyLoginResponse>; cancelLastOperation(timeoutRacer: TimeoutRacer): Promise<void>; dispose(): Promise<void>; } /** * Defines the different timeouts for every request. */ const DEFAULT_TIMEOUTS: {[key in keyof OpenYoloApi]: number} = { retrieve: 3000, save: 3000, disableAutoSignIn: 3000, hintsAvailable: 3000, hint: 3000, proxyLogin: 10000, cancelLastOperation: 3000 }; // This is a hack to be able to list the values of a "const enum" const RENDER_MODES: RenderMode[] = [RenderMode.bottomSheet, RenderMode.navPopout, RenderMode.fullScreen]; /** * Sanitzes the input for renderMode, selecting the default one if invalid. */ function verifyOrDetectRenderMode(renderMode: RenderMode|null): RenderMode { if (renderMode && RENDER_MODES.indexOf(renderMode) !== -1) { return renderMode; } const isNested = window.parent !== window; if (isNested) { return RenderMode.fullScreen; } const isMobile = navigator.userAgent.match(MOBILE_USER_AGENT_REGEX); if (isMobile) { return RenderMode.bottomSheet; } else { return RenderMode.navPopout; } } /** * Provides access to the user's preferred credential provider, in order to * retrieve credentials. */ export class OpenYoloApiImpl implements OpenYoloWithTimeoutApi { private disposed: boolean = false; /** The fallback when navigator.credentials should be used. */ private navigatorCredentials: OpenYoloApi; constructor( private frameManager: ProviderFrameElement, private channel: SecureChannel, fallbackApi?: OpenYoloApi) { this.navigatorCredentials = fallbackApi || createNavigatorCredentialsApi(); } async hintsAvailable( options: OpenYoloCredentialHintOptions, timeoutRacer: TimeoutRacer): Promise<boolean> { this.checkNotDisposed(); const request = new HintAvailableRequest(this.frameManager, this.channel); try { return await request.dispatch(options, timeoutRacer); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } else if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.hintsAvailable(options); } throw e; } } async hint( options: OpenYoloCredentialHintOptions, timeoutRacer: TimeoutRacer): Promise<OpenYoloCredential> { this.checkNotDisposed(); const request = new HintRequest(this.frameManager, this.channel); try { return await request.dispatch(options, timeoutRacer); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } else if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.hint(options); } throw e; } } async retrieve( options: OpenYoloCredentialRequestOptions, timeoutRacer: TimeoutRacer): Promise<OpenYoloCredential> { this.checkNotDisposed(); const request = new CredentialRequest(this.frameManager, this.channel); try { return await request.dispatch(options, timeoutRacer); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } else if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.retrieve(options); } throw e; } } async save(credential: OpenYoloCredential, timeoutRacer: TimeoutRacer) { this.checkNotDisposed(); const request = new CredentialSave(this.frameManager, this.channel); try { return await request.dispatch(credential, timeoutRacer); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } else if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.save(credential); } throw e; } } async proxyLogin(credential: OpenYoloCredential, timeoutRacer: TimeoutRacer): Promise<OpenYoloProxyLoginResponse> { this.checkNotDisposed(); const request = new ProxyLogin(this.frameManager, this.channel); try { return await request.dispatch(credential, timeoutRacer); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } else if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.proxyLogin(credential); } throw e; } } async disableAutoSignIn(timeoutRacer: TimeoutRacer) { this.checkNotDisposed(); const request = new DisableAutoSignIn(this.frameManager, this.channel); // Disable both navigator.credentials and provider as it is not known // whichever will be used in the next retrieve. try { const providerDisableAutoSignIn = request.dispatch(undefined, timeoutRacer); const browserDisableAutoSignIn = this.navigatorCredentials.disableAutoSignIn(); await Promise.all([providerDisableAutoSignIn, browserDisableAutoSignIn]); } catch (e) { if (timeoutRacer.hasTimedOut()) { // Cancel last operation so it doesn't remain pending. this.cancelLastOperationWithoutTimeout(); } throw e; } } async cancelLastOperation(timeoutRacer: TimeoutRacer) { this.checkNotDisposed(); const request = new CancelLastOperationRequest(this.frameManager, this.channel); try { return await request.dispatch(undefined, timeoutRacer); } catch (e) { if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.cancelLastOperation(); } throw e; } } private async cancelLastOperationWithoutTimeout() { this.checkNotDisposed(); const request = new CancelLastOperationRequest(this.frameManager, this.channel); try { return await request.dispatch(undefined, undefined); } catch (e) { if (e['type'] === OpenYoloErrorType.browserWrappingRequired) { return this.navigatorCredentials.cancelLastOperation(); } throw e; } } dispose(): Promise<void> { if (this.disposed) { return Promise.resolve(); } this.channel.dispose(); this.frameManager.dispose(); return Promise.resolve(); } private checkNotDisposed() { if (this.disposed) { throw OpenYoloInternalError.clientDisposed().toExposedError(); } } } export interface OnDemandOpenYoloApi extends OpenYoloApi { /** * Sets the provider URL. */ setProviderUrlBase(providerUrlBase: string): void; /** * Sets the features to enable for the current session. */ setFeatureConfig(featuresToEnable: string[]): void; /** * Sets the render mode, or null if the default one should be used. */ setRenderMode(renderMode: RenderMode|null): void; /** * Sets a custom timeouts, or 0 to disable timeouts. */ setTimeouts(timeoutMs: number|null): void; /** * Resets the current instantiation of the API. */ reset(): void; } /** * Wraps a promise for a CredentialsApiImpl, which is initialized on the first * usage of the API. This allows an implementation of CredentialsApi to be * directly exported from the module as a constant, without triggering * immediate instantiation when the module is loaded. */ export class InitializeOnDemandApi implements OnDemandOpenYoloApi { private providerUrlBase: string = 'https://provider.openyolo.org'; private featuresToEnable: string[] = []; private implPromise: Promise<OpenYoloWithTimeoutApi>|null = null; private renderMode: RenderMode|null = null; /** * Custom timeouts defined by the client. When null, the predefined timeouts * are used. */ private customTimeoutsMs: number|null = null; constructor() { // Register the handler for ping verification automatically on module load. respondToHandshake(window); } /** * Create the open yolo API based on the parameters given. It will always open * the provider page to check the user's configuration, and initialize the * correct implementation of OpenYolo based on the result. */ static createOpenYoloApi( timeoutRacer: TimeoutRacer, providerUrlBase: string, featuresToEnable: string[], renderMode: RenderMode|null, preloadRequest?: PreloadRequest): Promise<OpenYoloWithTimeoutApi> { let frameManager: ProviderFrameElement|null = null; // Sanitize input. const renderModeSanitized = verifyOrDetectRenderMode(renderMode); const instanceId = generateId(); // It is not great to use promise here. But using try/catch and await, it is // not possible to properly dispose of a potentially initialized // frameManager if an error happens in the way. I have no idea why, but the // typechecking engine of TypeScript considers that the framemanager can // never be initialized within the try block. return Promise.resolve() .then(() => { return timeoutRacer.race(sha256(instanceId)); }) .then((instanceIdHash) => { let featureConfig: FeatureConfig|undefined = undefined; if (featuresToEnable.length > 0) { featureConfig = {'feature': featuresToEnable}; } frameManager = new ProviderFrameElement( document, instanceIdHash, window.location.origin, renderModeSanitized, providerUrlBase, featureConfig, preloadRequest); return timeoutRacer.race(SecureChannel.clientConnect( window, frameManager.getContentWindow(), instanceId, instanceIdHash)); }) .then((channel) => { return new OpenYoloApiImpl(frameManager!, channel); }) .catch((e) => { // Dispose of the frame managerif it was created. if (frameManager !== null) { frameManager.dispose(); } timeoutRacer.rethrowUnlessTimeoutError(e); // Convert the timeout error. throw OpenYoloInternalError.requestTimeoutOnInitialization() .toExposedError(); }); } setProviderUrlBase(providerUrlBase: string) { this.providerUrlBase = providerUrlBase; this.reset(); } setFeatureConfig(featuresToEnable: string[]) { this.featuresToEnable = featuresToEnable; this.reset(); } setRenderMode(renderMode: RenderMode|null) { this.renderMode = renderMode; this.reset(); } /** * Sets a global custom timeouts that will wrap every request. * @param timeoutMs Custom timeout, in milliseconds. */ setTimeouts(timeoutMs: number|null) { if (timeoutMs === null) { this.customTimeoutsMs = null; this.reset(); return; } // Perform sanitization on the developer provided value. if (typeof timeoutMs !== 'number' || timeoutMs < 0) { throw new Error( 'Invalid timeout. It must be a number greater than or equal to 0. ' + 'Setting it to 0 disable timeouts.'); } // Only trigger reset if the setting changes and goes to disabling timeout, // this is meant to retry without timeout a potentially failed // initialization. const shouldReset = this.customTimeoutsMs !== timeoutMs && timeoutMs === 0; this.customTimeoutsMs = timeoutMs; if (shouldReset) { this.reset(); } } reset() { if (!this.implPromise) { return; } let promise = this.implPromise; this.implPromise = null; promise.then((impl) => { impl.dispose(); }); } private init(timeoutRacer: TimeoutRacer, preloadRequest?: PreloadRequest): Promise<OpenYoloWithTimeoutApi> { if (!this.implPromise) { this.implPromise = InitializeOnDemandApi.createOpenYoloApi( timeoutRacer, this.providerUrlBase, this.featuresToEnable, this.renderMode, preloadRequest); } this.implPromise.catch((e) => { // If the initialization failed, reset so the next call could work. this.reset(); }); return this.implPromise; } private startCustomTimeoutRacer(defaultTimeoutMs: number): TimeoutRacer { return startTimeoutRacer( this.customTimeoutsMs !== null ? this.customTimeoutsMs : defaultTimeoutMs); } async hintsAvailable(options: OpenYoloCredentialHintOptions): Promise<boolean> { const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.hintsAvailable); const preloadRequest = {type: PreloadRequestType.hint, options}; const impl = await this.init(timeoutRacer, preloadRequest); return await impl.hintsAvailable(options, timeoutRacer); } async hint(options: OpenYoloCredentialHintOptions): Promise<OpenYoloCredential> { const preloadRequest = {type: PreloadRequestType.hint, options}; const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.hint); const impl = await this.init(timeoutRacer, preloadRequest); return await impl.hint(options, timeoutRacer); } async retrieve(options: OpenYoloCredentialRequestOptions): Promise<OpenYoloCredential> { const preloadRequest = {type: PreloadRequestType.retrieve, options}; const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.retrieve); const impl = await this.init(timeoutRacer, preloadRequest); return impl.retrieve(options, timeoutRacer); } async save(credential: OpenYoloCredential): Promise<void> { const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.save); const impl = await this.init(timeoutRacer); return impl.save(credential, timeoutRacer); } async disableAutoSignIn(): Promise<void> { const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.disableAutoSignIn); const impl = await this.init(timeoutRacer); return impl.disableAutoSignIn(timeoutRacer); } async proxyLogin(credential: OpenYoloCredential): Promise<OpenYoloProxyLoginResponse> { const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.proxyLogin); const impl = await this.init(timeoutRacer); return impl.proxyLogin(credential, timeoutRacer); } async cancelLastOperation(): Promise<void> { const timeoutRacer = this.startCustomTimeoutRacer(DEFAULT_TIMEOUTS.cancelLastOperation); const impl = await this.init(timeoutRacer); return impl.cancelLastOperation(timeoutRacer); } } /** * API implementation that immediately rejects all requests. */ export class FakeOpenYoloApi implements OnDemandOpenYoloApi { private readonly unsupportedBrowserPromise = Promise.reject( OpenYoloInternalError.unsupportedBrowser().toExposedError()); setProviderUrlBase(providerUrlBase: string) {} setFeatureConfig(featuresToEnable: string[]) {} setRenderMode(renderMode: RenderMode|null) {} setTimeouts(timeout: number): void {} reset() {} hintsAvailable(options: OpenYoloCredentialHintOptions): Promise<boolean> { return this.unsupportedBrowserPromise; } hint(options: OpenYoloCredentialHintOptions): Promise<OpenYoloCredential> { return this.unsupportedBrowserPromise; } retrieve(options: OpenYoloCredentialRequestOptions): Promise<OpenYoloCredential> { return this.unsupportedBrowserPromise; } save(credential: OpenYoloCredential): Promise<void> { return this.unsupportedBrowserPromise; } disableAutoSignIn(): Promise<void> { return this.unsupportedBrowserPromise; } cancelLastOperation(): Promise<void> { return this.unsupportedBrowserPromise; } proxyLogin(credential: OpenYoloCredential): Promise<OpenYoloProxyLoginResponse> { return this.unsupportedBrowserPromise; } } /** * Checks whether the core browser functionality required for OpenYOLO is * supported in the current context. */ export function isCompatibleBrowser(win: Window): boolean { const hasCryptoRandomImplementation = win.hasOwnProperty('crypto') && 'getRandomValues' in win.crypto; if (!hasCryptoRandomImplementation) { console.warn( 'The current browser does not provide ' + 'window.crypto.getRandomValues. This is required by the API to work.' + ' This is likely due to an old browser.'); } const hasCryptoSubtleImplementation = win.hasOwnProperty('crypto') && ('subtle' in win.crypto || 'webkitSubtle' in win.crypto); if (!hasCryptoSubtleImplementation) { console.warn( 'The current environment does not provide window.crypto.subtle. This ' + 'is required by the API to work. This is likely due to an old ' + 'browser, or running the API in an unsecure origin - only secure ' + 'origins (https: and localhost) provide crypto.subtle.'); } return hasCryptoRandomImplementation && hasCryptoSubtleImplementation; } export const openyolo: OnDemandOpenYoloApi = isCompatibleBrowser(window) ? new InitializeOnDemandApi() : new FakeOpenYoloApi();
the_stack
import {css, LitElement, PropertyValues} from 'lit'; import {property, queryAll} from 'lit/decorators.js'; import rough from 'roughjs'; import {Drawable, Options} from 'roughjs/bin/core'; import {RoughCanvas} from 'roughjs/bin/canvas'; import {RoughSVG} from 'roughjs/bin/svg'; export enum RenderType { CANVAS = 'canvas', SVG = 'svg' } export enum AnimationType { ACTIVE = 'active', ALWAYS = 'always', NONE = 'none', } export interface RoughSize { width: number, height: number } export interface RoughObj { roughFirstRendered: boolean roughParentEl: HTMLElement roughParentElSizePre: RoughSize } export interface RoughObjSvg extends RoughObj { roughEl: SVGSVGElement roughInstance: RoughSVG } export interface RoughObjCanvas extends RoughObj { roughEl: HTMLCanvasElement roughInstance: RoughCanvas } export abstract class HandDrawnBase extends LitElement { @queryAll('.rough') private roughParentElArray: HTMLElement[] | undefined; @property() protected renderType: RenderType = RenderType.SVG; @property() protected animationType: AnimationType = AnimationType.ALWAYS; @property({state:true}) protected isFocus = false; @property({state:true}) protected isMouseIn = false; private _roughOps: Options = {}; @property({type: Object}) get roughOps() { return this._roughOps; }; set roughOps(value: Options) { const oldValue = this._roughOps; this.roughOpsOrigin = {...this.roughOpsDefault, ...value}; // console.log('!!', this.roughOpsDefault, value, JSON.parse(JSON.stringify(this.roughOpsOrigin))); this._roughOps = JSON.parse(JSON.stringify(this.roughOpsOrigin)) || {}; this.requestUpdate('roughOps', oldValue); } private seed = Math.floor(Math.random() * 2 ** 31); protected animationIntervalTime = 200; protected roughObjArray: (RoughObjSvg | RoughObjCanvas)[] = []; private drawInterval: NodeJS.Timeout | null = null; private resizeTimeout: NodeJS.Timeout | null = null; private resizePreTimestamp: number = 0; protected roughPadding: number = 2; protected resizeHandler = this.resizeHandlerTmp.bind(this); protected roughOpsOrigin: Options = {}; protected roughOpsDefault: Options = { bowing: 0.5, roughness: 0.8, stroke: '#363636', strokeWidth: 1, fillStyle: 'zigzag', fillWeight: 0.3, hachureGap: 4, }; constructor() { super(); this.fontLoadListener(); } protected firstUpdated(_changedProperties: PropertyValues) { super.firstUpdated(_changedProperties); this.roughInit(); } protected updated(_changedProperties: PropertyValues) { super.updated(_changedProperties); this.updateAnimationState(); setTimeout(() => { this.roughRender(); }, 0); } connectedCallback() { this.roughOps = this.roughOps || {}; super.connectedCallback(); window.addEventListener('resize', this.resizeHandler); this.addEventListener('mouseenter', this.mouseInHandler); this.addEventListener('focus', this.focusHandler); this.addEventListener('mouseleave', this.mouseOutHandler); this.addEventListener('blur', this.blurHandler); } disconnectedCallback() { super.connectedCallback(); window.removeEventListener('resize', this.resizeHandler); this.removeEventListener('mouseenter', this.mouseInHandler); this.removeEventListener('focus', this.focusHandler); this.removeEventListener('mouseleave', this.mouseOutHandler); this.removeEventListener('blur', this.blurHandler); } private fontLoadListener() { (<any>document).fonts.ready.then(() => { this.roughRender(); }); } private resizeHandlerTmp() { const now = Date.now(); if (now - this.resizePreTimestamp > this.animationIntervalTime) { this.roughRender(); this.resizePreTimestamp = now; } if (this.resizeTimeout) { clearTimeout(this.resizeTimeout); this.resizeTimeout = null; } this.resizeTimeout = setTimeout(() => { this.roughRender(); }, this.animationIntervalTime); } protected mouseInHandler() { this.isMouseIn = true; this.updateAnimationState(); } protected mouseOutHandler() { this.isMouseIn = false; this.updateAnimationState(); } protected focusHandler() { if (!this.isFocus) { // console.log('focus', this.roughOps, this.roughOpsOrigin); this.roughOps.stroke = '#000'; if (this.roughOps.strokeWidth !== undefined) { this.roughOps.strokeWidth = (this.roughOpsOrigin.strokeWidth || 0) + 1; } this.isFocus = true; this.updateAnimationState(); } } protected blurHandler() { if (this.isFocus) { this.isFocus = false; // console.log('blur', this.roughOps, this.roughOpsOrigin); this.roughOps.stroke = this.roughOpsOrigin.stroke; if (this.roughOps.strokeWidth !== undefined) { this.roughOps.strokeWidth = this.roughOpsOrigin.strokeWidth; } this.roughRender(true); this.updateAnimationState(); } } protected updateAnimationState() { if (this.animationType === AnimationType.ALWAYS) { this.roughOps.seed = 0; this.performAnimation(true); } else if (this.animationType === AnimationType.ACTIVE) { this.roughOps.seed = 0; this.performAnimation(this.isFocus || this.isMouseIn); } else if (this.animationType === AnimationType.NONE) { this.performAnimation(false); if (this.roughOps.seed !== this.seed) { this.roughOps.seed = this.seed; this.roughRender(true); } else { this.roughRender(this.isFocus || this.isMouseIn); } } } private performAnimation(isStart = true) { if (isStart) { if (!this.drawInterval) { this.drawInterval = setInterval(() => { this.roughRender(true); }, this.animationIntervalTime); } } else { if (this.drawInterval) { clearInterval(this.drawInterval); this.drawInterval = null; } } } private roughInit() { if (this.roughParentElArray && this.roughParentElArray.length > 0) { for (let roughParentEl of this.roughParentElArray) { switch (this.renderType) { case RenderType.CANVAS: { const roughDrawEl = document.createElement('canvas'); roughDrawEl.classList.add('rough-context'); roughParentEl.append(roughDrawEl); const roughDrawInstance = rough.canvas(roughDrawEl); this.roughObjArray.push({ roughFirstRendered: false, roughParentEl: roughParentEl, roughEl: roughDrawEl, roughInstance: roughDrawInstance, roughParentElSizePre: { width: roughParentEl.clientWidth||roughParentEl.getBoundingClientRect().width, height: roughParentEl.clientHeight||roughParentEl.getBoundingClientRect().height } }); break; } case RenderType.SVG: { const roughDrawEl = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); roughDrawEl.classList.add('rough-context'); roughParentEl.append(roughDrawEl); const roughDrawInstance = rough.svg(roughDrawEl); this.roughObjArray.push({ roughFirstRendered: false, roughParentEl: roughParentEl, roughEl: roughDrawEl, roughInstance: roughDrawInstance, roughParentElSizePre: { width: roughParentEl.clientWidth||roughParentEl.getBoundingClientRect().width, height: roughParentEl.clientHeight||roughParentEl.getBoundingClientRect().height } }); break; } } } } } protected roughRender(isForce: boolean = false) { for (let roughObj of this.roughObjArray) { const size = { width: roughObj.roughParentEl.clientWidth, height: roughObj.roughParentEl.clientHeight }; if (isForce || !roughObj.roughFirstRendered || size.width !== roughObj.roughParentElSizePre.width || size.height !== roughObj.roughParentElSizePre.height) { this.roughSizeOne(roughObj); this.roughDrawOne(roughObj); roughObj.roughFirstRendered = true; } roughObj.roughParentElSizePre.width = size.width; roughObj.roughParentElSizePre.height = size.height; } } protected roughSizeOne(roughObj: RoughObjSvg | RoughObjCanvas) { const size = { width: roughObj.roughParentEl.clientWidth, height: roughObj.roughParentEl.clientHeight }; roughObj.roughEl.style.width = size.width + 'px'; roughObj.roughEl.style.height = size.height + 'px'; roughObj.roughEl.setAttribute('width', String(size.width)); roughObj.roughEl.setAttribute('height', String(size.height)); } protected roughDrawOne(roughObj: RoughObjSvg | RoughObjCanvas, roughOps?: Options) { const size = { width: roughObj.roughParentEl.clientWidth, height: roughObj.roughParentEl.clientHeight }; if (roughObj.roughEl instanceof HTMLCanvasElement) { roughObj.roughEl.getContext('2d')?.clearRect(0, 0, this.clientWidth, this.clientHeight); } const nodeArray: (Drawable | SVGGElement)[] = []; nodeArray.push(roughObj.roughInstance.rectangle(this.roughPadding, this.roughPadding, size.width - this.roughPadding * 2, size.height - this.roughPadding * 2, roughOps || this.roughOps)); if (roughObj.roughEl instanceof SVGSVGElement) { roughObj.roughEl.innerHTML = ''; for (let node of nodeArray) { roughObj.roughEl.appendChild(<Node>node); } } } static get styles() { return css` * { padding: 0; margin: 0; box-sizing: border-box; -webkit-tap-highlight-color: rgba(255, 0, 0, 0); } ::-webkit-scrollbar { width: 4px; height: 4px; } ::-webkit-scrollbar-track { border-radius: 4px; } ::-webkit-scrollbar-thumb { border-radius: 4px; background: #999; } ::-webkit-scrollbar-thumb:hover { background: #999; } ::-webkit-scrollbar-thumb:active { background: #999; } ::-webkit-scrollbar-thumb:window-inactive { background: #999; } :host { display: inline-block; padding: 0; margin: 0; box-sizing: border-box; position: relative; } .slot { font: inherit; } .rough { position: relative; } .rough > .rough-context { position: absolute; overflow: hidden; top: 0; left: 0; right: 0; bottom: 0; z-index: -1; } `; } }
the_stack
import assert from 'assert' import seed from 'seed-random' import {Item, Algorithm, newDoc, canInsertNow, getArray, mergeInto, localDelete, Doc, yjsMod, automerge, yjs, printDebugStats, sync9, Id} from './crdts' /// TESTS let errored = false const runTests = (algName: string, alg: Algorithm) => { // Separate scope for namespace protection. const random = seed('ssx') const randInt = (n: number) => Math.floor(random() * n) const randArrItem = (arr: any[] | string) => arr[randInt(arr.length)] const randBool = (weight: number = 0.5) => random() < weight const makeItem = <T>(content: T, idOrAgent: string | Id, originLeft: Id | null, originRight: Id | null, amSeq: number, sync9Parent: Id | null = originLeft, sync9InsertAfter: boolean = true): Item<T> => ({ content, id: typeof idOrAgent === 'string' ? [idOrAgent, 0] : idOrAgent, isDeleted: false, originLeft: alg === sync9 ? sync9Parent : originLeft, originRight, insertAfter: sync9InsertAfter, seq: amSeq ?? -1, // Only for AM. }) const integrateFuzzOnce = <T>(ops: Item<T>[], expectedResult: T[]): number => { let variants = 1 const doc = newDoc() // Scan ops looking for candidates to integrate for (let numIntegrated = 0; numIntegrated < ops.length; numIntegrated++) { const candidates = [] for (const op of ops) { if (canInsertNow(op, doc)) { candidates.push(op) } } assert(candidates.length > 0) variants *= candidates.length // console.log('doc version', doc.version, 'candidates', candidates) // Pick one const op = candidates[randInt(candidates.length)] // console.log(op, doc.version) alg.integrate(doc, op) } // alg.printDoc(doc) try { assert.deepStrictEqual(getArray(doc), expectedResult) } catch(e) { console.log() alg.printDoc(doc) throw e } // console.log(variants) return variants // Rough guess at the number of orderings } const integrateFuzz = <T>(ops: Item<T>[], expectedResult: T[]) => { // Integrate the passed items a bunch of times, in different orders. let variants = integrateFuzzOnce(ops, expectedResult) for (let i = 1; i < Math.min(variants * 3, 100); i++) { let newVariants = integrateFuzzOnce(ops, expectedResult) variants = Math.max(variants, newVariants) } } const test = (fn: () => void) => { if (alg.ignoreTests && alg.ignoreTests.includes(fn.name)) { process.stdout.write(`SKIPPING ${fn.name}\n`) } else { process.stdout.write(`running ${fn.name} ...`) try { fn() process.stdout.write(`PASS\n`) } catch (e) { process.stdout.write(`FAIL:\n`) console.log(e.stack) errored = true } } } const smoke = () => { const doc = newDoc() alg.integrate(doc, makeItem('a', ['A', 0], null, null, 0)) alg.integrate(doc, makeItem('b', ['A', 1], ['A', 0], null, 1)) assert.deepStrictEqual(getArray(doc), ['a', 'b']) } const smokeMerge = () => { const doc = newDoc() alg.integrate(doc, makeItem('a', ['A', 0], null, null, 0)) alg.integrate(doc, makeItem('b', ['A', 1], ['A', 0], null, 1)) const doc2 = newDoc() mergeInto(alg, doc2, doc) assert.deepStrictEqual(getArray(doc2), ['a', 'b']) } const concurrentAvsB = () => { const a = makeItem('a', 'A', null, null, 0) const b = makeItem('b', 'B', null, null, 0) integrateFuzz([a, b], ['a', 'b']) } const interleavingForward = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a', ['A', 1], ['A', 0], null, 1), makeItem('a', ['A', 2], ['A', 1], null, 2), makeItem('b', ['B', 0], null, null, 0), makeItem('b', ['B', 1], ['B', 0], null, 1), makeItem('b', ['B', 2], ['B', 1], null, 2), ] integrateFuzz(ops, ['a', 'a', 'a', 'b', 'b', 'b']) } // Other variant with changed object IDs. The order should not be // dependent on the IDs of these items. I'd love to find a better way // to test this. const interleavingForward2 = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a', ['X', 0], ['A', 0], null, 1), makeItem('a', ['Y', 0], ['X', 0], null, 2), makeItem('b', ['B', 0], null, null, 0), makeItem('b', ['C', 0], ['B', 0], null, 1), makeItem('b', ['D', 0], ['C', 0], null, 2), ] integrateFuzz(ops, ['a', 'a', 'a', 'b', 'b', 'b']) } const interleavingBackward = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a', ['A', 1], null, ['A', 0], 1), makeItem('a', ['A', 2], null, ['A', 1], 2), makeItem('b', ['B', 0], null, null, 0), makeItem('b', ['B', 1], null, ['B', 0], 1), makeItem('b', ['B', 2], null, ['B', 1], 2), ] integrateFuzz(ops, ['a', 'a', 'a', 'b', 'b', 'b']) } const interleavingBackward2 = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a', ['X', 0], null, ['A', 0], 1, ['A', 0], false), makeItem('b', ['B', 0], null, null, 0), makeItem('b', ['B', 1], null, ['B', 0], 1, ['B', 0], false), ] integrateFuzz(ops, ['a', 'a', 'b', 'b']) } const withTails = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a0', ['A', 1], null, ['A', 0], 1, ['A', 0], false), // left makeItem('a1', ['A', 2], ['A', 0], null, 2), // right makeItem('b', ['B', 0], null, null, 0), makeItem('b0', ['B', 1], null, ['B', 0], 1, ['B', 0], false), // left makeItem('b1', ['B', 2], ['B', 0], null, 2), // right ] integrateFuzz(ops, ['a0', 'a', 'a1', 'b0', 'b', 'b1']) } const withTails2 = () => { const ops = [ makeItem('a', ['A', 0], null, null, 0), makeItem('a0', ['A', 1], null, ['A', 0], 1, ['A', 0], false), // left makeItem('a1', ['A', 2], ['A', 0], null, 2), // right makeItem('b', ['B', 0], null, null, 0), makeItem('b0', ['1', 0], null, ['B', 0], 1, ['B', 0], false), // left makeItem('b1', ['B', 1], ['B', 0], null, 2), // right ] integrateFuzz(ops, ['a0', 'a', 'a1', 'b0', 'b', 'b1']) } const localVsConcurrent = () => { // Check what happens when a top level concurrent change interacts // with a more localised change. (C vs D) const a = makeItem('a', 'A', null, null, 0) const c = makeItem('c', 'C', null, null, 0) // How do these two get ordered? const b = makeItem('b', 'B', null, null, 0) // Concurrent with a and c const d = makeItem('d', 'D', ['A', 0], ['C', 0], 1) // in between a and c // [a, b, d, c] would also be acceptable. integrateFuzz([a, b, c, d], ['a', 'd', 'b', 'c']) } const fuzzer1 = () => { const ops = [ makeItem(3, ['0', 0], null, null, 0), makeItem(5, ['1', 0], null, null, 0), makeItem(9, ['1', 1], null, ['1', 0], 1), makeItem(1, ['2', 0], null, null, 0), makeItem(4, ['2', 1], ['0', 0], ['2', 0], 1), makeItem(10, ['1', 2], ['2', 1], ['1', 1], 2), makeItem(7, ['2', 2], ['2', 1], ['2', 0], 2), ] const doc = newDoc<number>() ops.forEach(op => alg.integrate(doc, op)) console.log(getArray(doc)) } const fuzzSequential = () => { const doc = newDoc() let expectedContent: string[] = [] const alphabet = 'xyz123' const agents = 'ABCDE' let nextContent = 1 for (let i = 0; i < 1000; i++) { // console.log(i) // console.log(doc) if (doc.length === 0 || randBool(0.5)) { // insert const pos = randInt(doc.length + 1) // const content: string = randArrItem(alphabet) const content = ''+nextContent++ const agent = randArrItem(agents) // console.log('insert', agent, pos, `'${content}'`) alg.localInsert(doc, agent, pos, content) expectedContent.splice(pos, 0, content) } else { // Delete const pos = randInt(doc.length) const agent = randArrItem(agents) // console.log('delete', pos) localDelete(doc, agent, pos) expectedContent.splice(pos, 1) } // console.log('->', doc) // alg.printDoc(doc) assert.deepStrictEqual(doc.length, expectedContent.length) assert.deepStrictEqual(getArray(doc), expectedContent) } } const fuzzMultidoc = () => { const agents = ['A', 'B', 'C'] for (let j = 0; j < 10; j++) { process.stdout.write('.') const docs = new Array(3).fill(null).map((_, i) => { const doc: Doc<number> & {agent: string} = newDoc() as any doc.agent = agents[i] return doc }) const randDoc = () => docs[randInt(docs.length)] let nextItem = 0 // console.log(docs) for (let i = 0; i < 1000; i++) { // console.log(i) // if (i % 100 === 0) console.log(i) // Generate some random operations for (let j = 0; j < 3; j++) { const doc = randDoc() // if (doc.length === 0 || randBool(0.5)) { if (true) { // insert const pos = randInt(doc.length + 1) const content = ++nextItem // console.log('insert', agent, pos, content) alg.localInsert(doc, doc.agent, pos, content) } else { // Delete - disabled for now because mergeInto doesn't support deletes const pos = randInt(doc.length) // console.log('delete', pos) localDelete(doc, doc.agent, pos) } } // Pick a pair of documents and merge them const a = randDoc() const b = randDoc() if (a !== b) { // console.log('merging', a.agent, b.agent) mergeInto(alg, a, b) mergeInto(alg, b, a) try { assert.deepStrictEqual(getArray(a), getArray(b)) } catch (e) { console.log('\n') alg.printDoc(a) console.log('\n ---------------\n') alg.printDoc(b) throw e } } } } } console.log(`--- Running tests for ${algName} ---`) const tests = [ smoke, smokeMerge, concurrentAvsB, interleavingForward, interleavingForward2, interleavingBackward, interleavingBackward2, withTails, withTails2, localVsConcurrent, fuzzSequential, fuzzMultidoc ] tests.forEach(test) // interleavingBackwardSync9() // withTails2() // withTails2Sync9() // fuzzSequential() // fuzzMultidoc() // fuzzer1() console.log('\n\n') } runTests('yjsmod', yjsMod) runTests('yjs', yjs) runTests('automerge', automerge) runTests('sync9', sync9) // console.log('hits', hits, 'misses', misses) printDebugStats() process.exit(errored ? 1 : 0)
the_stack
import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K]; }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */ DateTime: any; /** Cursor for paging through collections */ ConnectionCursor: any; }; export type UpworkJobsSearchCriterion = { __typename?: 'UpworkJobsSearchCriterion'; id?: Maybe<Scalars['ID']>; employeeId: Scalars['String']; category?: Maybe<Scalars['String']>; categoryId?: Maybe<Scalars['String']>; occupation?: Maybe<Scalars['String']>; occupationId?: Maybe<Scalars['String']>; jobType: Scalars['String']; keyword: Scalars['String']; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive: Scalars['Boolean']; isArchived: Scalars['Boolean']; employee: Employee; }; export type Employee = { __typename?: 'Employee'; id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive: Scalars['Boolean']; isArchived: Scalars['Boolean']; upworkJobSearchCriteria: Array<UpworkJobsSearchCriterion>; upworkJobSearchCriteriaAggregate: EmployeeUpworkJobSearchCriteriaAggregateResponse; }; export type EmployeeUpworkJobSearchCriteriaArgs = { paging?: Maybe<OffsetPaging>; filter?: Maybe<UpworkJobsSearchCriterionFilter>; sorting?: Maybe<Array<UpworkJobsSearchCriterionSort>>; }; export type EmployeeUpworkJobSearchCriteriaAggregateArgs = { filter?: Maybe<UpworkJobsSearchCriterionAggregateFilter>; }; export type OffsetPaging = { /** Limit the number of records returned */ limit?: Maybe<Scalars['Int']>; /** Offset to start returning records from */ offset?: Maybe<Scalars['Int']>; }; export type UpworkJobsSearchCriterionFilter = { and?: Maybe<Array<UpworkJobsSearchCriterionFilter>>; or?: Maybe<Array<UpworkJobsSearchCriterionFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type IdFilterComparison = { is?: Maybe<Scalars['Boolean']>; isNot?: Maybe<Scalars['Boolean']>; eq?: Maybe<Scalars['ID']>; neq?: Maybe<Scalars['ID']>; gt?: Maybe<Scalars['ID']>; gte?: Maybe<Scalars['ID']>; lt?: Maybe<Scalars['ID']>; lte?: Maybe<Scalars['ID']>; like?: Maybe<Scalars['ID']>; notLike?: Maybe<Scalars['ID']>; iLike?: Maybe<Scalars['ID']>; notILike?: Maybe<Scalars['ID']>; in?: Maybe<Array<Scalars['ID']>>; notIn?: Maybe<Array<Scalars['ID']>>; }; export type StringFieldComparison = { is?: Maybe<Scalars['Boolean']>; isNot?: Maybe<Scalars['Boolean']>; eq?: Maybe<Scalars['String']>; neq?: Maybe<Scalars['String']>; gt?: Maybe<Scalars['String']>; gte?: Maybe<Scalars['String']>; lt?: Maybe<Scalars['String']>; lte?: Maybe<Scalars['String']>; like?: Maybe<Scalars['String']>; notLike?: Maybe<Scalars['String']>; iLike?: Maybe<Scalars['String']>; notILike?: Maybe<Scalars['String']>; in?: Maybe<Array<Scalars['String']>>; notIn?: Maybe<Array<Scalars['String']>>; }; export type BooleanFieldComparison = { is?: Maybe<Scalars['Boolean']>; isNot?: Maybe<Scalars['Boolean']>; }; export type UpworkJobsSearchCriterionSort = { field: UpworkJobsSearchCriterionSortFields; direction: SortDirection; nulls?: Maybe<SortNulls>; }; export enum UpworkJobsSearchCriterionSortFields { Id = 'id', EmployeeId = 'employeeId', JobType = 'jobType', IsActive = 'isActive', IsArchived = 'isArchived' } /** Sort Directions */ export enum SortDirection { Asc = 'ASC', Desc = 'DESC' } /** Sort Nulls Options */ export enum SortNulls { NullsFirst = 'NULLS_FIRST', NullsLast = 'NULLS_LAST' } export type UpworkJobsSearchCriterionAggregateFilter = { and?: Maybe<Array<UpworkJobsSearchCriterionAggregateFilter>>; or?: Maybe<Array<UpworkJobsSearchCriterionAggregateFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type JobPost = { __typename?: 'JobPost'; id?: Maybe<Scalars['ID']>; providerCode: Scalars['String']; providerJobId: Scalars['String']; title: Scalars['String']; description: Scalars['String']; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; url?: Maybe<Scalars['String']>; budget?: Maybe<Scalars['String']>; duration?: Maybe<Scalars['String']>; workload?: Maybe<Scalars['String']>; skills?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; subcategory?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; clientFeedback?: Maybe<Scalars['String']>; clientReviewsCount?: Maybe<Scalars['Float']>; clientJobsPosted?: Maybe<Scalars['Float']>; clientPastHires?: Maybe<Scalars['Float']>; clientPaymentVerificationStatus?: Maybe<Scalars['Boolean']>; searchCategory?: Maybe<Scalars['String']>; searchCategoryId?: Maybe<Scalars['String']>; searchOccupation?: Maybe<Scalars['String']>; searchOccupationId?: Maybe<Scalars['String']>; searchJobType?: Maybe<Scalars['String']>; searchKeyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive: Scalars['Boolean']; isArchived: Scalars['Boolean']; }; export type EmployeeJobPost = { __typename?: 'EmployeeJobPost'; id?: Maybe<Scalars['ID']>; employeeId: Scalars['String']; jobPostId: Scalars['String']; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode: Scalars['String']; providerJobId: Scalars['String']; isApplied?: Maybe<Scalars['Boolean']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive: Scalars['Boolean']; isArchived: Scalars['Boolean']; jobPost: JobPost; employee: Employee; }; export type DeleteManyResponse = { __typename?: 'DeleteManyResponse'; /** The number of records deleted. */ deletedCount: Scalars['Int']; }; export type JobPostDeleteResponse = { __typename?: 'JobPostDeleteResponse'; id?: Maybe<Scalars['ID']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; title?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; url?: Maybe<Scalars['String']>; budget?: Maybe<Scalars['String']>; duration?: Maybe<Scalars['String']>; workload?: Maybe<Scalars['String']>; skills?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; subcategory?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; clientFeedback?: Maybe<Scalars['String']>; clientReviewsCount?: Maybe<Scalars['Float']>; clientJobsPosted?: Maybe<Scalars['Float']>; clientPastHires?: Maybe<Scalars['Float']>; clientPaymentVerificationStatus?: Maybe<Scalars['Boolean']>; searchCategory?: Maybe<Scalars['String']>; searchCategoryId?: Maybe<Scalars['String']>; searchOccupation?: Maybe<Scalars['String']>; searchOccupationId?: Maybe<Scalars['String']>; searchJobType?: Maybe<Scalars['String']>; searchKeyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpdateManyResponse = { __typename?: 'UpdateManyResponse'; /** The number of records updated. */ updatedCount: Scalars['Int']; }; export type JobPostEdge = { __typename?: 'JobPostEdge'; /** The node containing the JobPost */ node: JobPost; /** Cursor for this node. */ cursor: Scalars['ConnectionCursor']; }; export type PageInfo = { __typename?: 'PageInfo'; /** true if paging forward and there are more records. */ hasNextPage?: Maybe<Scalars['Boolean']>; /** true if paging backwards and there are more records. */ hasPreviousPage?: Maybe<Scalars['Boolean']>; /** The cursor of the first returned record. */ startCursor?: Maybe<Scalars['ConnectionCursor']>; /** The cursor of the last returned record. */ endCursor?: Maybe<Scalars['ConnectionCursor']>; }; export type JobPostConnection = { __typename?: 'JobPostConnection'; /** Paging information */ pageInfo: PageInfo; /** Array of edges. */ edges: Array<JobPostEdge>; /** Fetch total count of records */ totalCount: Scalars['Int']; }; export type JobPostCountAggregate = { __typename?: 'JobPostCountAggregate'; id?: Maybe<Scalars['Int']>; providerCode?: Maybe<Scalars['Int']>; providerJobId?: Maybe<Scalars['Int']>; jobDateCreated?: Maybe<Scalars['Int']>; jobStatus?: Maybe<Scalars['Int']>; jobType?: Maybe<Scalars['Int']>; country?: Maybe<Scalars['Int']>; createdAt?: Maybe<Scalars['Int']>; updatedAt?: Maybe<Scalars['Int']>; isActive?: Maybe<Scalars['Int']>; isArchived?: Maybe<Scalars['Int']>; }; export type JobPostMinAggregate = { __typename?: 'JobPostMinAggregate'; id?: Maybe<Scalars['ID']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type JobPostMaxAggregate = { __typename?: 'JobPostMaxAggregate'; id?: Maybe<Scalars['ID']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type JobPostAggregateResponse = { __typename?: 'JobPostAggregateResponse'; count?: Maybe<JobPostCountAggregate>; min?: Maybe<JobPostMinAggregate>; max?: Maybe<JobPostMaxAggregate>; }; export type UpworkJobsSearchCriterionDeleteResponse = { __typename?: 'UpworkJobsSearchCriterionDeleteResponse'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; categoryId?: Maybe<Scalars['String']>; occupation?: Maybe<Scalars['String']>; occupationId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; keyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpworkJobsSearchCriterionEdge = { __typename?: 'UpworkJobsSearchCriterionEdge'; /** The node containing the UpworkJobsSearchCriterion */ node: UpworkJobsSearchCriterion; /** Cursor for this node. */ cursor: Scalars['ConnectionCursor']; }; export type UpworkJobsSearchCriterionConnection = { __typename?: 'UpworkJobsSearchCriterionConnection'; /** Paging information */ pageInfo: PageInfo; /** Array of edges. */ edges: Array<UpworkJobsSearchCriterionEdge>; /** Fetch total count of records */ totalCount: Scalars['Int']; }; export type UpworkJobsSearchCriterionCountAggregate = { __typename?: 'UpworkJobsSearchCriterionCountAggregate'; id?: Maybe<Scalars['Int']>; employeeId?: Maybe<Scalars['Int']>; jobType?: Maybe<Scalars['Int']>; isActive?: Maybe<Scalars['Int']>; isArchived?: Maybe<Scalars['Int']>; }; export type UpworkJobsSearchCriterionMinAggregate = { __typename?: 'UpworkJobsSearchCriterionMinAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; }; export type UpworkJobsSearchCriterionMaxAggregate = { __typename?: 'UpworkJobsSearchCriterionMaxAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; }; export type UpworkJobsSearchCriterionAggregateResponse = { __typename?: 'UpworkJobsSearchCriterionAggregateResponse'; count?: Maybe<UpworkJobsSearchCriterionCountAggregate>; min?: Maybe<UpworkJobsSearchCriterionMinAggregate>; max?: Maybe<UpworkJobsSearchCriterionMaxAggregate>; }; export type EmployeeDeleteResponse = { __typename?: 'EmployeeDeleteResponse'; id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type EmployeeEdge = { __typename?: 'EmployeeEdge'; /** The node containing the Employee */ node: Employee; /** Cursor for this node. */ cursor: Scalars['ConnectionCursor']; }; export type EmployeeConnection = { __typename?: 'EmployeeConnection'; /** Paging information */ pageInfo: PageInfo; /** Array of edges. */ edges: Array<EmployeeEdge>; /** Fetch total count of records */ totalCount: Scalars['Int']; }; export type EmployeeCountAggregate = { __typename?: 'EmployeeCountAggregate'; id?: Maybe<Scalars['Int']>; externalEmployeeId?: Maybe<Scalars['Int']>; firstName?: Maybe<Scalars['Int']>; lastName?: Maybe<Scalars['Int']>; jobType?: Maybe<Scalars['Int']>; createdAt?: Maybe<Scalars['Int']>; updatedAt?: Maybe<Scalars['Int']>; isActive?: Maybe<Scalars['Int']>; isArchived?: Maybe<Scalars['Int']>; }; export type EmployeeMinAggregate = { __typename?: 'EmployeeMinAggregate'; id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type EmployeeMaxAggregate = { __typename?: 'EmployeeMaxAggregate'; id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type EmployeeAggregateResponse = { __typename?: 'EmployeeAggregateResponse'; count?: Maybe<EmployeeCountAggregate>; min?: Maybe<EmployeeMinAggregate>; max?: Maybe<EmployeeMaxAggregate>; }; export type EmployeeUpworkJobSearchCriteriaCountAggregate = { __typename?: 'EmployeeUpworkJobSearchCriteriaCountAggregate'; id?: Maybe<Scalars['Int']>; employeeId?: Maybe<Scalars['Int']>; jobType?: Maybe<Scalars['Int']>; isActive?: Maybe<Scalars['Int']>; isArchived?: Maybe<Scalars['Int']>; }; export type EmployeeUpworkJobSearchCriteriaMinAggregate = { __typename?: 'EmployeeUpworkJobSearchCriteriaMinAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; }; export type EmployeeUpworkJobSearchCriteriaMaxAggregate = { __typename?: 'EmployeeUpworkJobSearchCriteriaMaxAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; }; export type EmployeeUpworkJobSearchCriteriaAggregateResponse = { __typename?: 'EmployeeUpworkJobSearchCriteriaAggregateResponse'; count?: Maybe<EmployeeUpworkJobSearchCriteriaCountAggregate>; min?: Maybe<EmployeeUpworkJobSearchCriteriaMinAggregate>; max?: Maybe<EmployeeUpworkJobSearchCriteriaMaxAggregate>; }; export type EmployeeJobPostDeleteResponse = { __typename?: 'EmployeeJobPostDeleteResponse'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobPostId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; isApplied?: Maybe<Scalars['Boolean']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type EmployeeJobPostEdge = { __typename?: 'EmployeeJobPostEdge'; /** The node containing the EmployeeJobPost */ node: EmployeeJobPost; /** Cursor for this node. */ cursor: Scalars['ConnectionCursor']; }; export type EmployeeJobPostConnection = { __typename?: 'EmployeeJobPostConnection'; /** Paging information */ pageInfo: PageInfo; /** Array of edges. */ edges: Array<EmployeeJobPostEdge>; /** Fetch total count of records */ totalCount: Scalars['Int']; }; export type EmployeeJobPostCountAggregate = { __typename?: 'EmployeeJobPostCountAggregate'; id?: Maybe<Scalars['Int']>; employeeId?: Maybe<Scalars['Int']>; jobPostId?: Maybe<Scalars['Int']>; jobDateCreated?: Maybe<Scalars['Int']>; jobStatus?: Maybe<Scalars['Int']>; jobType?: Maybe<Scalars['Int']>; providerCode?: Maybe<Scalars['Int']>; providerJobId?: Maybe<Scalars['Int']>; isApplied?: Maybe<Scalars['Int']>; appliedDate?: Maybe<Scalars['Int']>; createdAt?: Maybe<Scalars['Int']>; updatedAt?: Maybe<Scalars['Int']>; isActive?: Maybe<Scalars['Int']>; isArchived?: Maybe<Scalars['Int']>; }; export type EmployeeJobPostMinAggregate = { __typename?: 'EmployeeJobPostMinAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobPostId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type EmployeeJobPostMaxAggregate = { __typename?: 'EmployeeJobPostMaxAggregate'; id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobPostId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; }; export type EmployeeJobPostAggregateResponse = { __typename?: 'EmployeeJobPostAggregateResponse'; count?: Maybe<EmployeeJobPostCountAggregate>; min?: Maybe<EmployeeJobPostMinAggregate>; max?: Maybe<EmployeeJobPostMaxAggregate>; }; export type Query = { __typename?: 'Query'; jobPost?: Maybe<JobPost>; jobPosts: JobPostConnection; jobPostAggregate: JobPostAggregateResponse; upworkJobsSearchCriterion?: Maybe<UpworkJobsSearchCriterion>; upworkJobsSearchCriteria: UpworkJobsSearchCriterionConnection; upworkJobsSearchCriterionAggregate: UpworkJobsSearchCriterionAggregateResponse; employee?: Maybe<Employee>; employees: EmployeeConnection; employeeAggregate: EmployeeAggregateResponse; employeeJobPost?: Maybe<EmployeeJobPost>; employeeJobPosts: EmployeeJobPostConnection; employeeJobPostAggregate: EmployeeJobPostAggregateResponse; }; export type QueryJobPostArgs = { id: Scalars['ID']; }; export type QueryJobPostsArgs = { paging?: Maybe<CursorPaging>; filter?: Maybe<JobPostFilter>; sorting?: Maybe<Array<JobPostSort>>; }; export type QueryJobPostAggregateArgs = { filter?: Maybe<JobPostAggregateFilter>; }; export type QueryUpworkJobsSearchCriterionArgs = { id: Scalars['ID']; }; export type QueryUpworkJobsSearchCriteriaArgs = { paging?: Maybe<CursorPaging>; filter?: Maybe<UpworkJobsSearchCriterionFilter>; sorting?: Maybe<Array<UpworkJobsSearchCriterionSort>>; }; export type QueryUpworkJobsSearchCriterionAggregateArgs = { filter?: Maybe<UpworkJobsSearchCriterionAggregateFilter>; }; export type QueryEmployeeArgs = { id: Scalars['ID']; }; export type QueryEmployeesArgs = { paging?: Maybe<CursorPaging>; filter?: Maybe<EmployeeFilter>; sorting?: Maybe<Array<EmployeeSort>>; }; export type QueryEmployeeAggregateArgs = { filter?: Maybe<EmployeeAggregateFilter>; }; export type QueryEmployeeJobPostArgs = { id: Scalars['ID']; }; export type QueryEmployeeJobPostsArgs = { paging?: Maybe<CursorPaging>; filter?: Maybe<EmployeeJobPostFilter>; sorting?: Maybe<Array<EmployeeJobPostSort>>; }; export type QueryEmployeeJobPostAggregateArgs = { filter?: Maybe<EmployeeJobPostAggregateFilter>; }; export type CursorPaging = { /** Paginate before opaque cursor */ before?: Maybe<Scalars['ConnectionCursor']>; /** Paginate after opaque cursor */ after?: Maybe<Scalars['ConnectionCursor']>; /** Paginate first */ first?: Maybe<Scalars['Int']>; /** Paginate last */ last?: Maybe<Scalars['Int']>; }; export type JobPostFilter = { and?: Maybe<Array<JobPostFilter>>; or?: Maybe<Array<JobPostFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type DateFieldComparison = { is?: Maybe<Scalars['Boolean']>; isNot?: Maybe<Scalars['Boolean']>; eq?: Maybe<Scalars['DateTime']>; neq?: Maybe<Scalars['DateTime']>; gt?: Maybe<Scalars['DateTime']>; gte?: Maybe<Scalars['DateTime']>; lt?: Maybe<Scalars['DateTime']>; lte?: Maybe<Scalars['DateTime']>; in?: Maybe<Array<Scalars['DateTime']>>; notIn?: Maybe<Array<Scalars['DateTime']>>; between?: Maybe<DateFieldComparisonBetween>; notBetween?: Maybe<DateFieldComparisonBetween>; }; export type DateFieldComparisonBetween = { lower: Scalars['DateTime']; upper: Scalars['DateTime']; }; export type JobPostSort = { field: JobPostSortFields; direction: SortDirection; nulls?: Maybe<SortNulls>; }; export enum JobPostSortFields { Id = 'id', ProviderCode = 'providerCode', ProviderJobId = 'providerJobId', JobDateCreated = 'jobDateCreated', JobStatus = 'jobStatus', JobType = 'jobType', Country = 'country', CreatedAt = 'createdAt', UpdatedAt = 'updatedAt', IsActive = 'isActive', IsArchived = 'isArchived' } export type JobPostAggregateFilter = { and?: Maybe<Array<JobPostAggregateFilter>>; or?: Maybe<Array<JobPostAggregateFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type EmployeeFilter = { and?: Maybe<Array<EmployeeFilter>>; or?: Maybe<Array<EmployeeFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type EmployeeSort = { field: EmployeeSortFields; direction: SortDirection; nulls?: Maybe<SortNulls>; }; export enum EmployeeSortFields { Id = 'id', ExternalEmployeeId = 'externalEmployeeId', FirstName = 'firstName', LastName = 'lastName', JobType = 'jobType', CreatedAt = 'createdAt', UpdatedAt = 'updatedAt', IsActive = 'isActive', IsArchived = 'isArchived' } export type EmployeeAggregateFilter = { and?: Maybe<Array<EmployeeAggregateFilter>>; or?: Maybe<Array<EmployeeAggregateFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type EmployeeJobPostFilter = { and?: Maybe<Array<EmployeeJobPostFilter>>; or?: Maybe<Array<EmployeeJobPostFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobPostId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; isApplied?: Maybe<BooleanFieldComparison>; appliedDate?: Maybe<DateFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; jobPost?: Maybe<EmployeeJobPostFilterJobPostFilter>; employee?: Maybe<EmployeeJobPostFilterEmployeeFilter>; }; export type EmployeeJobPostFilterJobPostFilter = { and?: Maybe<Array<EmployeeJobPostFilterJobPostFilter>>; or?: Maybe<Array<EmployeeJobPostFilterJobPostFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type EmployeeJobPostFilterEmployeeFilter = { and?: Maybe<Array<EmployeeJobPostFilterEmployeeFilter>>; or?: Maybe<Array<EmployeeJobPostFilterEmployeeFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type EmployeeJobPostSort = { field: EmployeeJobPostSortFields; direction: SortDirection; nulls?: Maybe<SortNulls>; }; export enum EmployeeJobPostSortFields { Id = 'id', EmployeeId = 'employeeId', JobPostId = 'jobPostId', JobDateCreated = 'jobDateCreated', JobStatus = 'jobStatus', JobType = 'jobType', ProviderCode = 'providerCode', ProviderJobId = 'providerJobId', IsApplied = 'isApplied', AppliedDate = 'appliedDate', CreatedAt = 'createdAt', UpdatedAt = 'updatedAt', IsActive = 'isActive', IsArchived = 'isArchived' } export type EmployeeJobPostAggregateFilter = { and?: Maybe<Array<EmployeeJobPostAggregateFilter>>; or?: Maybe<Array<EmployeeJobPostAggregateFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobPostId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; isApplied?: Maybe<BooleanFieldComparison>; appliedDate?: Maybe<DateFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type Mutation = { __typename?: 'Mutation'; deleteOneJobPost: JobPostDeleteResponse; deleteManyJobPosts: DeleteManyResponse; updateOneJobPost: JobPost; updateManyJobPosts: UpdateManyResponse; createOneJobPost: JobPost; createManyJobPosts: Array<JobPost>; deleteOneUpworkJobsSearchCriterion: UpworkJobsSearchCriterionDeleteResponse; deleteManyUpworkJobsSearchCriteria: DeleteManyResponse; updateOneUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; updateManyUpworkJobsSearchCriteria: UpdateManyResponse; createOneUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; createManyUpworkJobsSearchCriteria: Array<UpworkJobsSearchCriterion>; removeEmployeeFromUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; setEmployeeOnUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; deleteOneEmployee: EmployeeDeleteResponse; deleteManyEmployees: DeleteManyResponse; updateOneEmployee: Employee; updateManyEmployees: UpdateManyResponse; createOneEmployee: Employee; createManyEmployees: Array<Employee>; removeUpworkJobSearchCriteriaFromEmployee: Employee; addUpworkJobSearchCriteriaToEmployee: Employee; deleteOneEmployeeJobPost: EmployeeJobPostDeleteResponse; deleteManyEmployeeJobPosts: DeleteManyResponse; updateOneEmployeeJobPost: EmployeeJobPost; updateManyEmployeeJobPosts: UpdateManyResponse; createOneEmployeeJobPost: EmployeeJobPost; createManyEmployeeJobPosts: Array<EmployeeJobPost>; removeJobPostFromEmployeeJobPost: EmployeeJobPost; removeEmployeeFromEmployeeJobPost: EmployeeJobPost; setJobPostOnEmployeeJobPost: EmployeeJobPost; setEmployeeOnEmployeeJobPost: EmployeeJobPost; }; export type MutationDeleteOneJobPostArgs = { input: DeleteOneInput; }; export type MutationDeleteManyJobPostsArgs = { input: DeleteManyJobPostsInput; }; export type MutationUpdateOneJobPostArgs = { input: UpdateOneJobPostInput; }; export type MutationUpdateManyJobPostsArgs = { input: UpdateManyJobPostsInput; }; export type MutationCreateOneJobPostArgs = { input: CreateOneJobPostInput; }; export type MutationCreateManyJobPostsArgs = { input: CreateManyJobPostsInput; }; export type MutationDeleteOneUpworkJobsSearchCriterionArgs = { input: DeleteOneInput; }; export type MutationDeleteManyUpworkJobsSearchCriteriaArgs = { input: DeleteManyUpworkJobsSearchCriteriaInput; }; export type MutationUpdateOneUpworkJobsSearchCriterionArgs = { input: UpdateOneUpworkJobsSearchCriterionInput; }; export type MutationUpdateManyUpworkJobsSearchCriteriaArgs = { input: UpdateManyUpworkJobsSearchCriteriaInput; }; export type MutationCreateOneUpworkJobsSearchCriterionArgs = { input: CreateOneUpworkJobsSearchCriterionInput; }; export type MutationCreateManyUpworkJobsSearchCriteriaArgs = { input: CreateManyUpworkJobsSearchCriteriaInput; }; export type MutationRemoveEmployeeFromUpworkJobsSearchCriterionArgs = { input: RelationInput; }; export type MutationSetEmployeeOnUpworkJobsSearchCriterionArgs = { input: RelationInput; }; export type MutationDeleteOneEmployeeArgs = { input: DeleteOneInput; }; export type MutationDeleteManyEmployeesArgs = { input: DeleteManyEmployeesInput; }; export type MutationUpdateOneEmployeeArgs = { input: UpdateOneEmployeeInput; }; export type MutationUpdateManyEmployeesArgs = { input: UpdateManyEmployeesInput; }; export type MutationCreateOneEmployeeArgs = { input: CreateOneEmployeeInput; }; export type MutationCreateManyEmployeesArgs = { input: CreateManyEmployeesInput; }; export type MutationRemoveUpworkJobSearchCriteriaFromEmployeeArgs = { input: RelationsInput; }; export type MutationAddUpworkJobSearchCriteriaToEmployeeArgs = { input: RelationsInput; }; export type MutationDeleteOneEmployeeJobPostArgs = { input: DeleteOneInput; }; export type MutationDeleteManyEmployeeJobPostsArgs = { input: DeleteManyEmployeeJobPostsInput; }; export type MutationUpdateOneEmployeeJobPostArgs = { input: UpdateOneEmployeeJobPostInput; }; export type MutationUpdateManyEmployeeJobPostsArgs = { input: UpdateManyEmployeeJobPostsInput; }; export type MutationCreateOneEmployeeJobPostArgs = { input: CreateOneEmployeeJobPostInput; }; export type MutationCreateManyEmployeeJobPostsArgs = { input: CreateManyEmployeeJobPostsInput; }; export type MutationRemoveJobPostFromEmployeeJobPostArgs = { input: RelationInput; }; export type MutationRemoveEmployeeFromEmployeeJobPostArgs = { input: RelationInput; }; export type MutationSetJobPostOnEmployeeJobPostArgs = { input: RelationInput; }; export type MutationSetEmployeeOnEmployeeJobPostArgs = { input: RelationInput; }; export type DeleteOneInput = { /** The id of the record to delete. */ id: Scalars['ID']; }; export type DeleteManyJobPostsInput = { /** Filter to find records to delete */ filter: JobPostDeleteFilter; }; export type JobPostDeleteFilter = { and?: Maybe<Array<JobPostDeleteFilter>>; or?: Maybe<Array<JobPostDeleteFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneJobPostInput = { /** The id of the record to update */ id: Scalars['ID']; /** The update to apply. */ update: UpdateJobPost; }; export type UpdateJobPost = { id?: Maybe<Scalars['ID']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; title?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; url?: Maybe<Scalars['String']>; budget?: Maybe<Scalars['String']>; duration?: Maybe<Scalars['String']>; workload?: Maybe<Scalars['String']>; skills?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; subcategory?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; clientFeedback?: Maybe<Scalars['String']>; clientReviewsCount?: Maybe<Scalars['Float']>; clientJobsPosted?: Maybe<Scalars['Float']>; clientPastHires?: Maybe<Scalars['Float']>; clientPaymentVerificationStatus?: Maybe<Scalars['Boolean']>; searchCategory?: Maybe<Scalars['String']>; searchCategoryId?: Maybe<Scalars['String']>; searchOccupation?: Maybe<Scalars['String']>; searchOccupationId?: Maybe<Scalars['String']>; searchJobType?: Maybe<Scalars['String']>; searchKeyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpdateManyJobPostsInput = { /** Filter used to find fields to update */ filter: JobPostUpdateFilter; /** The update to apply to all records found using the filter */ update: UpdateJobPost; }; export type JobPostUpdateFilter = { and?: Maybe<Array<JobPostUpdateFilter>>; or?: Maybe<Array<JobPostUpdateFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type CreateOneJobPostInput = { /** The record to create */ jobPost: CreateJobPost; }; export type CreateJobPost = { id?: Maybe<Scalars['ID']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; title?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; url?: Maybe<Scalars['String']>; budget?: Maybe<Scalars['String']>; duration?: Maybe<Scalars['String']>; workload?: Maybe<Scalars['String']>; skills?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; subcategory?: Maybe<Scalars['String']>; country?: Maybe<Scalars['String']>; clientFeedback?: Maybe<Scalars['String']>; clientReviewsCount?: Maybe<Scalars['Float']>; clientJobsPosted?: Maybe<Scalars['Float']>; clientPastHires?: Maybe<Scalars['Float']>; clientPaymentVerificationStatus?: Maybe<Scalars['Boolean']>; searchCategory?: Maybe<Scalars['String']>; searchCategoryId?: Maybe<Scalars['String']>; searchOccupation?: Maybe<Scalars['String']>; searchOccupationId?: Maybe<Scalars['String']>; searchJobType?: Maybe<Scalars['String']>; searchKeyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type CreateManyJobPostsInput = { /** Array of records to create */ jobPosts: Array<CreateJobPost>; }; export type DeleteManyUpworkJobsSearchCriteriaInput = { /** Filter to find records to delete */ filter: UpworkJobsSearchCriterionDeleteFilter; }; export type UpworkJobsSearchCriterionDeleteFilter = { and?: Maybe<Array<UpworkJobsSearchCriterionDeleteFilter>>; or?: Maybe<Array<UpworkJobsSearchCriterionDeleteFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneUpworkJobsSearchCriterionInput = { /** The id of the record to update */ id: Scalars['ID']; /** The update to apply. */ update: UpdateUpworkJobsSearchCriterion; }; export type UpdateUpworkJobsSearchCriterion = { id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; categoryId?: Maybe<Scalars['String']>; occupation?: Maybe<Scalars['String']>; occupationId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; keyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpdateManyUpworkJobsSearchCriteriaInput = { /** Filter used to find fields to update */ filter: UpworkJobsSearchCriterionUpdateFilter; /** The update to apply to all records found using the filter */ update: UpdateUpworkJobsSearchCriterion; }; export type UpworkJobsSearchCriterionUpdateFilter = { and?: Maybe<Array<UpworkJobsSearchCriterionUpdateFilter>>; or?: Maybe<Array<UpworkJobsSearchCriterionUpdateFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type CreateOneUpworkJobsSearchCriterionInput = { /** The record to create */ upworkJobsSearchCriterion: CreateUpworkJobsSearchCriterion; }; export type CreateUpworkJobsSearchCriterion = { id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; category?: Maybe<Scalars['String']>; categoryId?: Maybe<Scalars['String']>; occupation?: Maybe<Scalars['String']>; occupationId?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; keyword?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type CreateManyUpworkJobsSearchCriteriaInput = { /** Array of records to create */ upworkJobsSearchCriteria: Array<CreateUpworkJobsSearchCriterion>; }; export type RelationInput = { /** The id of the record. */ id: Scalars['ID']; /** The id of relation. */ relationId: Scalars['ID']; }; export type DeleteManyEmployeesInput = { /** Filter to find records to delete */ filter: EmployeeDeleteFilter; }; export type EmployeeDeleteFilter = { and?: Maybe<Array<EmployeeDeleteFilter>>; or?: Maybe<Array<EmployeeDeleteFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneEmployeeInput = { /** The id of the record to update */ id: Scalars['ID']; /** The update to apply. */ update: UpdateEmployee; }; export type UpdateEmployee = { id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpdateManyEmployeesInput = { /** Filter used to find fields to update */ filter: EmployeeUpdateFilter; /** The update to apply to all records found using the filter */ update: UpdateEmployee; }; export type EmployeeUpdateFilter = { and?: Maybe<Array<EmployeeUpdateFilter>>; or?: Maybe<Array<EmployeeUpdateFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type CreateOneEmployeeInput = { /** The record to create */ employee: CreateEmployee; }; export type CreateEmployee = { id?: Maybe<Scalars['ID']>; externalEmployeeId?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type CreateManyEmployeesInput = { /** Array of records to create */ employees: Array<CreateEmployee>; }; export type RelationsInput = { /** The id of the record. */ id: Scalars['ID']; /** The ids of the relations. */ relationIds: Array<Scalars['ID']>; }; export type DeleteManyEmployeeJobPostsInput = { /** Filter to find records to delete */ filter: EmployeeJobPostDeleteFilter; }; export type EmployeeJobPostDeleteFilter = { and?: Maybe<Array<EmployeeJobPostDeleteFilter>>; or?: Maybe<Array<EmployeeJobPostDeleteFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobPostId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; isApplied?: Maybe<BooleanFieldComparison>; appliedDate?: Maybe<DateFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneEmployeeJobPostInput = { /** The id of the record to update */ id: Scalars['ID']; /** The update to apply. */ update: UpdateEmployeeJobPost; }; export type UpdateEmployeeJobPost = { id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobPostId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; isApplied?: Maybe<Scalars['Boolean']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type UpdateManyEmployeeJobPostsInput = { /** Filter used to find fields to update */ filter: EmployeeJobPostUpdateFilter; /** The update to apply to all records found using the filter */ update: UpdateEmployeeJobPost; }; export type EmployeeJobPostUpdateFilter = { and?: Maybe<Array<EmployeeJobPostUpdateFilter>>; or?: Maybe<Array<EmployeeJobPostUpdateFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobPostId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; isApplied?: Maybe<BooleanFieldComparison>; appliedDate?: Maybe<DateFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type CreateOneEmployeeJobPostInput = { /** The record to create */ employeeJobPost: CreateEmployeeJobPost; }; export type CreateEmployeeJobPost = { id?: Maybe<Scalars['ID']>; employeeId?: Maybe<Scalars['String']>; jobPostId?: Maybe<Scalars['String']>; jobDateCreated?: Maybe<Scalars['DateTime']>; jobStatus?: Maybe<Scalars['String']>; jobType?: Maybe<Scalars['String']>; providerCode?: Maybe<Scalars['String']>; providerJobId?: Maybe<Scalars['String']>; isApplied?: Maybe<Scalars['Boolean']>; appliedDate?: Maybe<Scalars['DateTime']>; createdAt?: Maybe<Scalars['DateTime']>; updatedAt?: Maybe<Scalars['DateTime']>; isActive?: Maybe<Scalars['Boolean']>; isArchived?: Maybe<Scalars['Boolean']>; }; export type CreateManyEmployeeJobPostsInput = { /** Array of records to create */ employeeJobPosts: Array<CreateEmployeeJobPost>; }; export type Subscription = { __typename?: 'Subscription'; deletedOneJobPost: JobPostDeleteResponse; deletedManyJobPosts: DeleteManyResponse; updatedOneJobPost: JobPost; updatedManyJobPosts: UpdateManyResponse; createdJobPost: JobPost; deletedOneUpworkJobsSearchCriterion: UpworkJobsSearchCriterionDeleteResponse; deletedManyUpworkJobsSearchCriteria: DeleteManyResponse; updatedOneUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; updatedManyUpworkJobsSearchCriteria: UpdateManyResponse; createdUpworkJobsSearchCriterion: UpworkJobsSearchCriterion; deletedOneEmployee: EmployeeDeleteResponse; deletedManyEmployees: DeleteManyResponse; updatedOneEmployee: Employee; updatedManyEmployees: UpdateManyResponse; createdEmployee: Employee; deletedOneEmployeeJobPost: EmployeeJobPostDeleteResponse; deletedManyEmployeeJobPosts: DeleteManyResponse; updatedOneEmployeeJobPost: EmployeeJobPost; updatedManyEmployeeJobPosts: UpdateManyResponse; createdEmployeeJobPost: EmployeeJobPost; }; export type SubscriptionDeletedOneJobPostArgs = { input?: Maybe<DeleteOneJobPostSubscriptionFilterInput>; }; export type SubscriptionUpdatedOneJobPostArgs = { input?: Maybe<UpdateOneJobPostSubscriptionFilterInput>; }; export type SubscriptionCreatedJobPostArgs = { input?: Maybe<CreateJobPostSubscriptionFilterInput>; }; export type SubscriptionDeletedOneUpworkJobsSearchCriterionArgs = { input?: Maybe<DeleteOneUpworkJobsSearchCriterionSubscriptionFilterInput>; }; export type SubscriptionUpdatedOneUpworkJobsSearchCriterionArgs = { input?: Maybe<UpdateOneUpworkJobsSearchCriterionSubscriptionFilterInput>; }; export type SubscriptionCreatedUpworkJobsSearchCriterionArgs = { input?: Maybe<CreateUpworkJobsSearchCriterionSubscriptionFilterInput>; }; export type SubscriptionDeletedOneEmployeeArgs = { input?: Maybe<DeleteOneEmployeeSubscriptionFilterInput>; }; export type SubscriptionUpdatedOneEmployeeArgs = { input?: Maybe<UpdateOneEmployeeSubscriptionFilterInput>; }; export type SubscriptionCreatedEmployeeArgs = { input?: Maybe<CreateEmployeeSubscriptionFilterInput>; }; export type SubscriptionDeletedOneEmployeeJobPostArgs = { input?: Maybe<DeleteOneEmployeeJobPostSubscriptionFilterInput>; }; export type SubscriptionUpdatedOneEmployeeJobPostArgs = { input?: Maybe<UpdateOneEmployeeJobPostSubscriptionFilterInput>; }; export type SubscriptionCreatedEmployeeJobPostArgs = { input?: Maybe<CreateEmployeeJobPostSubscriptionFilterInput>; }; export type DeleteOneJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: JobPostSubscriptionFilter; }; export type JobPostSubscriptionFilter = { and?: Maybe<Array<JobPostSubscriptionFilter>>; or?: Maybe<Array<JobPostSubscriptionFilter>>; id?: Maybe<IdFilterComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; country?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: JobPostSubscriptionFilter; }; export type CreateJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: JobPostSubscriptionFilter; }; export type DeleteOneUpworkJobsSearchCriterionSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: UpworkJobsSearchCriterionSubscriptionFilter; }; export type UpworkJobsSearchCriterionSubscriptionFilter = { and?: Maybe<Array<UpworkJobsSearchCriterionSubscriptionFilter>>; or?: Maybe<Array<UpworkJobsSearchCriterionSubscriptionFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneUpworkJobsSearchCriterionSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: UpworkJobsSearchCriterionSubscriptionFilter; }; export type CreateUpworkJobsSearchCriterionSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: UpworkJobsSearchCriterionSubscriptionFilter; }; export type DeleteOneEmployeeSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeSubscriptionFilter; }; export type EmployeeSubscriptionFilter = { and?: Maybe<Array<EmployeeSubscriptionFilter>>; or?: Maybe<Array<EmployeeSubscriptionFilter>>; id?: Maybe<IdFilterComparison>; externalEmployeeId?: Maybe<StringFieldComparison>; firstName?: Maybe<StringFieldComparison>; lastName?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneEmployeeSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeSubscriptionFilter; }; export type CreateEmployeeSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeSubscriptionFilter; }; export type DeleteOneEmployeeJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeJobPostSubscriptionFilter; }; export type EmployeeJobPostSubscriptionFilter = { and?: Maybe<Array<EmployeeJobPostSubscriptionFilter>>; or?: Maybe<Array<EmployeeJobPostSubscriptionFilter>>; id?: Maybe<IdFilterComparison>; employeeId?: Maybe<StringFieldComparison>; jobPostId?: Maybe<StringFieldComparison>; jobDateCreated?: Maybe<DateFieldComparison>; jobStatus?: Maybe<StringFieldComparison>; jobType?: Maybe<StringFieldComparison>; providerCode?: Maybe<StringFieldComparison>; providerJobId?: Maybe<StringFieldComparison>; isApplied?: Maybe<BooleanFieldComparison>; appliedDate?: Maybe<DateFieldComparison>; createdAt?: Maybe<DateFieldComparison>; updatedAt?: Maybe<DateFieldComparison>; isActive?: Maybe<BooleanFieldComparison>; isArchived?: Maybe<BooleanFieldComparison>; }; export type UpdateOneEmployeeJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeJobPostSubscriptionFilter; }; export type CreateEmployeeJobPostSubscriptionFilterInput = { /** Specify to filter the records returned. */ filter: EmployeeJobPostSubscriptionFilter; }; export type EmployeeJobPostsQueryVariables = Exact<{ after: Scalars['ConnectionCursor']; first: Scalars['Int']; filter: EmployeeJobPostFilter; sorting?: Maybe<Array<EmployeeJobPostSort>>; }>; export type EmployeeJobPostsQuery = { __typename?: 'Query' } & { employeeJobPosts: { __typename?: 'EmployeeJobPostConnection' } & Pick< EmployeeJobPostConnection, 'totalCount' > & { pageInfo: { __typename?: 'PageInfo' } & Pick< PageInfo, 'hasNextPage' | 'hasPreviousPage' | 'startCursor' | 'endCursor' >; edges: Array< { __typename?: 'EmployeeJobPostEdge' } & { node: { __typename?: 'EmployeeJobPost' } & Pick< EmployeeJobPost, | 'id' | 'isApplied' | 'appliedDate' | 'createdAt' | 'updatedAt' | 'isActive' | 'isArchived' | 'providerCode' | 'providerJobId' | 'jobDateCreated' | 'jobStatus' | 'jobType' > & { employee: { __typename?: 'Employee' } & Pick< Employee, 'id' | 'externalEmployeeId' >; jobPost: { __typename?: 'JobPost' } & Pick< JobPost, | 'id' | 'providerCode' | 'providerJobId' | 'title' | 'description' | 'jobDateCreated' | 'jobStatus' | 'jobType' | 'url' | 'budget' | 'duration' | 'workload' | 'skills' | 'category' | 'subcategory' | 'country' | 'clientFeedback' | 'clientReviewsCount' | 'clientJobsPosted' | 'clientPastHires' | 'clientPaymentVerificationStatus' >; }; } >; }; }; export type EmployeeJobPostsByEmployeeIdJobPostIdQueryVariables = Exact<{ employeeIdFilter: Scalars['String']; jobPostIdFilter: Scalars['String']; }>; export type EmployeeJobPostsByEmployeeIdJobPostIdQuery = { __typename?: 'Query'; } & { employeeJobPosts: { __typename?: 'EmployeeJobPostConnection' } & { edges: Array< { __typename?: 'EmployeeJobPostEdge' } & { node: { __typename?: 'EmployeeJobPost' } & Pick< EmployeeJobPost, 'id' | 'isActive' | 'isArchived' >; } >; }; }; export type EmployeeQueryVariables = Exact<{ [key: string]: never }>; export type EmployeeQuery = { __typename?: 'Query' } & { employees: { __typename?: 'EmployeeConnection' } & { pageInfo: { __typename?: 'PageInfo' } & Pick< PageInfo, 'hasNextPage' | 'hasPreviousPage' | 'startCursor' | 'endCursor' >; edges: Array< { __typename?: 'EmployeeEdge' } & { node: { __typename?: 'Employee' } & Pick< Employee, 'id' | 'externalEmployeeId' | 'firstName' | 'lastName' >; } >; }; }; export type EmployeeByExternalEmployeeIdQueryVariables = Exact<{ externalEmployeeIdFilter: Scalars['String']; }>; export type EmployeeByExternalEmployeeIdQuery = { __typename?: 'Query' } & { employees: { __typename?: 'EmployeeConnection' } & Pick< EmployeeConnection, 'totalCount' > & { edges: Array< { __typename?: 'EmployeeEdge' } & { node: { __typename?: 'Employee' } & Pick< Employee, 'id' | 'externalEmployeeId' >; } >; }; }; export type EmployeeByNameQueryVariables = Exact<{ firstNameFilter: Scalars['String']; lastNameFilter: Scalars['String']; }>; export type EmployeeByNameQuery = { __typename?: 'Query' } & { employees: { __typename?: 'EmployeeConnection' } & Pick< EmployeeConnection, 'totalCount' > & { edges: Array< { __typename?: 'EmployeeEdge' } & { node: { __typename?: 'Employee' } & Pick< Employee, 'id' | 'firstName' | 'lastName' | 'externalEmployeeId' >; } >; }; }; export type UpdateOneEmployeeMutationVariables = Exact<{ input: UpdateOneEmployeeInput; }>; export type UpdateOneEmployeeMutation = { __typename?: 'Mutation' } & { updateOneEmployee: { __typename?: 'Employee' } & Pick< Employee, | 'externalEmployeeId' | 'isActive' | 'isArchived' | 'firstName' | 'lastName' >; }; export type UpdateOneEmployeeJobPostMutationVariables = Exact<{ input: UpdateOneEmployeeJobPostInput; }>; export type UpdateOneEmployeeJobPostMutation = { __typename?: 'Mutation' } & { updateOneEmployeeJobPost: { __typename?: 'EmployeeJobPost' } & Pick< EmployeeJobPost, | 'employeeId' | 'jobPostId' | 'isActive' | 'isArchived' | 'isApplied' | 'appliedDate' >; }; export type DeleteManyUpworkJobsSearchCriteriaMutationVariables = Exact<{ input: DeleteManyUpworkJobsSearchCriteriaInput; }>; export type DeleteManyUpworkJobsSearchCriteriaMutation = { __typename?: 'Mutation'; } & { deleteManyUpworkJobsSearchCriteria: { __typename?: 'DeleteManyResponse'; } & Pick<DeleteManyResponse, 'deletedCount'>; }; export type CreateManyUpworkJobsSearchCriteriaMutationVariables = Exact<{ input: CreateManyUpworkJobsSearchCriteriaInput; }>; export type CreateManyUpworkJobsSearchCriteriaMutation = { __typename?: 'Mutation'; } & { createManyUpworkJobsSearchCriteria: Array< { __typename?: 'UpworkJobsSearchCriterion' } & Pick< UpworkJobsSearchCriterion, 'id' > >; }; export type JobPostsQueryVariables = Exact<{ providerCodeFilter: Scalars['String']; providerJobIdFilter: Scalars['String']; }>; export type JobPostsQuery = { __typename?: 'Query' } & { jobPosts: { __typename?: 'JobPostConnection' } & { edges: Array< { __typename?: 'JobPostEdge' } & { node: { __typename?: 'JobPost' } & Pick< JobPost, 'id' | 'isActive' | 'isArchived' >; } >; }; }; export const EmployeeJobPostsDocument: DocumentNode< EmployeeJobPostsQuery, EmployeeJobPostsQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'employeeJobPosts' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'after' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'ConnectionCursor' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'first' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'Int' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'filter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'EmployeeJobPostFilter' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'sorting' } }, type: { kind: 'ListType', type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'EmployeeJobPostSort' } } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employeeJobPosts' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'paging' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'after' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'after' } } }, { kind: 'ObjectField', name: { kind: 'Name', value: 'first' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'first' } } } ] } }, { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'filter' } } }, { kind: 'Argument', name: { kind: 'Name', value: 'sorting' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'sorting' } } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'totalCount' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'pageInfo' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'hasNextPage' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'hasPreviousPage' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'startCursor' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'endCursor' }, arguments: [], directives: [] } ] } }, { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isApplied' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'appliedDate' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'createdAt' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isActive' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isArchived' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'employee' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'externalEmployeeId' }, arguments: [], directives: [] } ] } }, { kind: 'Field', name: { kind: 'Name', value: 'providerCode' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'providerJobId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobDateCreated' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobStatus' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobType' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobPost' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'providerCode' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'providerJobId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'title' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'description' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobDateCreated' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobStatus' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobType' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'url' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'budget' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'duration' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'workload' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'skills' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'category' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'subcategory' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'country' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'clientFeedback' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'clientReviewsCount' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'clientJobsPosted' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'clientPastHires' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'clientPaymentVerificationStatus' }, arguments: [], directives: [] } ] } } ] } } ] } } ] } } ] } } ] }; export const EmployeeJobPostsByEmployeeIdJobPostIdDocument: DocumentNode< EmployeeJobPostsByEmployeeIdJobPostIdQuery, EmployeeJobPostsByEmployeeIdJobPostIdQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'employeeJobPostsByEmployeeIdJobPostId' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'employeeIdFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'jobPostIdFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employeeJobPosts' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'employeeId' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'employeeIdFilter' } } } ] } }, { kind: 'ObjectField', name: { kind: 'Name', value: 'jobPostId' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'jobPostIdFilter' } } } ] } } ] } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isActive' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isArchived' }, arguments: [], directives: [] } ] } } ] } } ] } } ] } } ] }; export const EmployeeDocument: DocumentNode< EmployeeQuery, EmployeeQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'employee' }, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employees' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'pageInfo' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'hasNextPage' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'hasPreviousPage' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'startCursor' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'endCursor' }, arguments: [], directives: [] } ] } }, { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'externalEmployeeId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'firstName' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'lastName' }, arguments: [], directives: [] } ] } } ] } } ] } } ] } } ] }; export const EmployeeByExternalEmployeeIdDocument: DocumentNode< EmployeeByExternalEmployeeIdQuery, EmployeeByExternalEmployeeIdQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'employeeByExternalEmployeeId' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'externalEmployeeIdFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employees' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'externalEmployeeId' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'externalEmployeeIdFilter' } } } ] } } ] } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'externalEmployeeId' }, arguments: [], directives: [] } ] } } ] } }, { kind: 'Field', name: { kind: 'Name', value: 'totalCount' }, arguments: [], directives: [] } ] } } ] } } ] }; export const EmployeeByNameDocument: DocumentNode< EmployeeByNameQuery, EmployeeByNameQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'employeeByName' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'firstNameFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'lastNameFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employees' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'firstName' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'firstNameFilter' } } } ] } }, { kind: 'ObjectField', name: { kind: 'Name', value: 'lastName' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'lastNameFilter' } } } ] } } ] } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'firstName' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'lastName' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'externalEmployeeId' }, arguments: [], directives: [] } ] } } ] } }, { kind: 'Field', name: { kind: 'Name', value: 'totalCount' }, arguments: [], directives: [] } ] } } ] } } ] }; export const UpdateOneEmployeeDocument: DocumentNode< UpdateOneEmployeeMutation, UpdateOneEmployeeMutationVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'updateOneEmployee' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'UpdateOneEmployeeInput' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'updateOneEmployee' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'externalEmployeeId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isActive' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isArchived' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'firstName' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'lastName' }, arguments: [], directives: [] } ] } } ] } } ] }; export const UpdateOneEmployeeJobPostDocument: DocumentNode< UpdateOneEmployeeJobPostMutation, UpdateOneEmployeeJobPostMutationVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'updateOneEmployeeJobPost' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'UpdateOneEmployeeJobPostInput' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'updateOneEmployeeJobPost' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'employeeId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'jobPostId' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isActive' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isArchived' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isApplied' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'appliedDate' }, arguments: [], directives: [] } ] } } ] } } ] }; export const DeleteManyUpworkJobsSearchCriteriaDocument: DocumentNode< DeleteManyUpworkJobsSearchCriteriaMutation, DeleteManyUpworkJobsSearchCriteriaMutationVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'deleteManyUpworkJobsSearchCriteria' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'DeleteManyUpworkJobsSearchCriteriaInput' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'deleteManyUpworkJobsSearchCriteria' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'deletedCount' }, arguments: [], directives: [] } ] } } ] } } ] }; export const CreateManyUpworkJobsSearchCriteriaDocument: DocumentNode< CreateManyUpworkJobsSearchCriteriaMutation, CreateManyUpworkJobsSearchCriteriaMutationVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'createManyUpworkJobsSearchCriteria' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'CreateManyUpworkJobsSearchCriteriaInput' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'createManyUpworkJobsSearchCriteria' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] } ] } } ] } } ] }; export const JobPostsDocument: DocumentNode< JobPostsQuery, JobPostsQueryVariables > = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'jobPosts' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'providerCodeFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'providerJobIdFilter' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } } }, directives: [] } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'jobPosts' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'providerCode' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'providerCodeFilter' } } } ] } }, { kind: 'ObjectField', name: { kind: 'Name', value: 'providerJobId' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'eq' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'providerJobIdFilter' } } } ] } } ] } } ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'edges' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'node' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isActive' }, arguments: [], directives: [] }, { kind: 'Field', name: { kind: 'Name', value: 'isArchived' }, arguments: [], directives: [] } ] } } ] } } ] } } ] } } ] };
the_stack
import 'module-alias/register'; import Serverless from 'serverless' import { config } from 'aws-sdk'; import { DynamoService } from './dynamo/dynamoService'; import { LambdaService } from './lambda/lambdaService'; import { IamService } from './iam/iamService'; import { DynamoStream, DynamoStreamType, IDynamoStream, StreamSpecification, Table } from './dynamo/types'; import { RolePolicy } from './iam/types'; import { EventSourcePosition } from './_base/EventSourcePosition'; import { EventSourceMappingState } from './lambda/types'; export class ServerlessDynamoStreamPlugin { readonly dynamoService: DynamoService; readonly lambdaService: LambdaService; readonly iamService: IamService; // Serverless parameters readonly serverless: Serverless; readonly options: Serverless.Options; /** * @description the key in serverless.yml */ readonly existingStreamKey: string = 'existingDynamoStream'; readonly requiredDynamoStreamPermissions = [ 'dynamodb:GetRecords', 'dynamodb:GetShardIterator', 'dynamodb:DescribeStream', 'dynamodb:ListStreams' ]; /** * @description hooks in the plugin command into the Serverless command lifecycle. */ readonly hooks: { [key: string]: any }; /** * @description exposes some commands for running it in the standalone mode. */ readonly commands: { [key: string]: any }; /** * @description number of milliseconds to wait for AWS to finalize all the things. */ readonly finalWaitPeriod: number = 60000; private readonly maxIamWaitAttempts: number = 3; private readonly iamWaitIntervalMillis: number = 5000; constructor(serverless: Serverless, options: Serverless.Options) { this.serverless = serverless; this.options = options; // set the plugin to be runnable as a command this.commands = { 'dynamo-stream': { usage: 'Creates and connects DynamoDB streams for pre-existing tables with AWS Lambdas', lifecycleEvents: ['connect'], }, }; // bind the lifecycle hooks this.hooks = { 'dynamo-stream:connect': this.run.bind(this), 'after:deploy:deploy': this.run.bind(this), }; // define the new event schema if serverless supports it if ((serverless as any).configSchemaHandler) { (serverless as any).configSchemaHandler.defineFunctionEvent('aws', 'existingDynamoStream', { type: 'object', properties: { tableName: { type: 'string' }, streamType: { type: 'string' }, startingPosition: { type: 'string' }, }, required: ['tableName', 'streamType', 'startingPosition'], additionalProperties: false, }); } // configure AWS. config.update({ region: serverless.service.provider.region, apiVersions: { dynamodb: '2012-08-10', } }); this.dynamoService = new DynamoService(); this.lambdaService = new LambdaService(); this.iamService = new IamService(); } async run(): Promise<boolean> { this.serverless.cli.log('dynamoStream:connect - connecting functions to DynamoDB streams'); const lambdaToStreams = this.getLambdaStreams(); // Exit early if there are no existing streams in serverless.yml if (Object.keys(lambdaToStreams).length <= 0) { return true; } this.serverless.cli.log(`The following functions need some connections: ${Object.keys(lambdaToStreams)}`); for (const [functionName, events] of Object.entries(lambdaToStreams)) { const functionObject = this.serverless.service.getFunction(functionName); const fullFunctionName = functionObject.name; for (const event of events) { try { // get a table stream specification let table = await this.getTable(event.tableName); // enable the stream if needed const updatedTable = await this.enableStreamIfNeeded(event.tableName, event.streamType, table.streamSpecification); if (updatedTable) { table = updatedTable; this.serverless.cli.log(`Updated the stream for table ${event.tableName} to ${event.streamType}`); } // get a table stream arn const streamArn = table?.latestStreamArn; if (!streamArn) { throw new Error('Failed to find the stream arn to connect the function to.'); } // get a function role name const lambdaRoleName = await this.getLambdaRoleName(fullFunctionName); this.serverless.cli.log(`Fetched role name ${lambdaRoleName} for lambda ${fullFunctionName}`); // get the role policy const rolePolicy = await this.getRolePolicy(lambdaRoleName); this.serverless.cli.log(`Found policy name ${rolePolicy.policyName} for lambda ${fullFunctionName}`); // add new permissions to the role policy if needed const newPermissionsAdded = await this.addPermissionsIfNeeded(rolePolicy, streamArn, lambdaRoleName); newPermissionsAdded ? this.serverless.cli.log(`Created a new policy for Role ${lambdaRoleName} to access the stream ${streamArn}`) : this.serverless.cli.log(`Role ${lambdaRoleName} already has a policy for ${streamArn}`); // IAM takes some time to propagate, // retrying the request and catching the error causes multiple mappings to be created, // fetching the policy document says the updated policy is there, where in reality the create mapping call fails, // so a real world solution is to wait until IAM catches up. // https://github.com/aws/aws-sdk-js/issues/850 if (newPermissionsAdded) { let attempts = 0; while (attempts <= this.maxIamWaitAttempts) { attempts ? this.serverless.cli.log('.') : this.serverless.cli.log('Hang in there, IAM takes some time to process new permissions.'); attempts += 1; await this.sleep(this.iamWaitIntervalMillis); } } const mappingCreatedOrActivated = await this.createOrActivateMappingIfNeeded(streamArn, fullFunctionName, event.startingPosition); mappingCreatedOrActivated ? this.serverless.cli.log(`Mapping of lambda ${fullFunctionName} to table ${event.tableName} stream is now active.`) : this.serverless.cli.log(`Active mapping lambda ${fullFunctionName} to table ${event.tableName} stream already exists.`); } catch (error) { this.serverless.cli.log(`Failed to connect lambda ${fullFunctionName} to table ${event.tableName}.` + ` Error: ${error.message ? error.message : error}`); } } } return true; } /** * @description add the permissions to the role policy if necessary. * @param rolePolicy the role policy to add the permissions to. * @param streamArn the stream arn to add the permissions for. * @param lambdaRoleName the role name of the lambda. */ private async addPermissionsIfNeeded(rolePolicy: RolePolicy, streamArn: string, lambdaRoleName: string): Promise<boolean> { // figure out if the stream permissions already exist on the stream const policyDocument = JSON.parse(decodeURIComponent(rolePolicy.policyDocument)); const alreadyAllowsDynamoStream = policyDocument.Statement .some((statement: any) => statement.Resource.includes(streamArn) && this.requiredDynamoStreamPermissions.every(requiredPermission => statement.Action.includes(requiredPermission)) && statement.Effect === 'Allow'); // add a new policy to the existing document if needed let newPermissionsAdded = false; if (!alreadyAllowsDynamoStream) { policyDocument.Statement.push({ Action: this.requiredDynamoStreamPermissions, Resource: [streamArn], Effect: 'Allow', }); // create the new policy on AWS rolePolicy.policyDocument = JSON.stringify(policyDocument); await this.iamService.putRolePolicy(rolePolicy); newPermissionsAdded = true; } return newPermissionsAdded; } /** * @description get a role policy object. * @param lambdaRoleName the name of the lambda role. */ private async getRolePolicy(lambdaRoleName: string): Promise<RolePolicy> { const policyNames = await this.iamService.listRolePolicies(lambdaRoleName); const policyName = policyNames.find(name => name.includes(this.serverless.service.getServiceName())); if (!policyName) { throw new Error('Couldn\'t find Serverless policy, please make sure Serverless deploy succeeds first.') } return this.iamService.getRolePolicy(lambdaRoleName, policyName); } /** * @description gets the role name of the lambda. * @param fullFunctionName the full lambda function name including the stage and the service. */ private async getLambdaRoleName(fullFunctionName: string): Promise<string> { const configuration = await this.lambdaService.getFunctionConfiguration(fullFunctionName); const functionRoleArn = configuration?.roleArn; if (!functionRoleArn) { throw new Error('Function configuration doesn\'t have a role.' + ' Please make sure Serverless deploy succeeds to deploy the lambdas first.'); } const fullLambdaRoleName = functionRoleArn?.split(':').pop(); const lambdaRoleName = fullLambdaRoleName?.split('/').pop(); if (!lambdaRoleName) { throw new Error(`Lambda role arn ${functionRoleArn} doesn\'t have a name.` + ` Make sure the right role is set on lambda ${fullFunctionName}.`); } return lambdaRoleName; } /** * @description returns an object containing a lambda name as a key and the array of streams as a value. */ getLambdaStreams(): { [key: string]: DynamoStream[] } { const lambdaToStreams: { [key: string]: DynamoStream[] } = {}; // find all lambdas that have a custom event in their attributes for (const functionName of this.serverless.service.getAllFunctions()) { const events = this.serverless.service.getAllEventsInFunction(functionName); const existingStreamEvents = events.filter(event => (event as any)[this.existingStreamKey]); if (existingStreamEvents.length > 0) { lambdaToStreams[functionName] = existingStreamEvents .map(event => new DynamoStream((event as any)[this.existingStreamKey] as IDynamoStream)); } } return lambdaToStreams; } /** * @description enables the DynamoDB stream if needed and the returns a new table if updated. * @param currentStream the current stream specification. * @param tableName the table name for the stream. * @param targetStreamType what we want the stream type to be. */ private async enableStreamIfNeeded( tableName: string, targetStreamType: DynamoStreamType, currentStream?: StreamSpecification, ): Promise<Table | undefined> { // update the stream if it's not enabled or its stream type is not what's specified in serverless.yml if (!currentStream || !currentStream.isEnabled || (currentStream.isEnabled && currentStream.viewType !== targetStreamType)) { let updateStream = new StreamSpecification({ isEnabled: true, viewType: targetStreamType, }); updateStream.isEnabled = true; return this.dynamoService.updateTable(tableName, updateStream); } else { return undefined; } } /** * @description returns the stream specification for the table. * @param tableName the table name to look for. * @throws an error when the table isn't found. */ private async getTable(tableName: string): Promise<Table> { const table = await this.dynamoService.describeTable(tableName); if (!table) { throw new Error(`Table ${tableName} is not found.`); } return table; } /** * @description creates a new mapping if it doesn't exist, or activates an inactive existing mapping. * @param streamArn the stream arn for the mapping. * @param fullFunctionName the function name to connect the mapping to. * @param startingPosition the starting position for the stream. */ private async createOrActivateMappingIfNeeded( streamArn: string, fullFunctionName: string, startingPosition: EventSourcePosition ): Promise<boolean> { const existingMappings = await this.lambdaService.listEventSourceMappings(fullFunctionName); let existingMapping = existingMappings.find(mapping => mapping.eventSourceArn === streamArn); let createdOrActivated = false; if (!existingMapping) { // create an active source mapping if it doesn't exist await this.lambdaService.createEventSourceMapping(streamArn, fullFunctionName, startingPosition); createdOrActivated = true; } else if (existingMapping && existingMapping.state !== EventSourceMappingState.ENABLED) { // activate an inactive mapping if it exists and it's not active if (!existingMapping.id) { throw new Error('Updating an event source mapping requires an id'); } await this.lambdaService.enableEventSourceMapping(existingMapping.id); createdOrActivated = true; } return createdOrActivated; } private sleep(ms: number) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } } module.exports = ServerlessDynamoStreamPlugin;
the_stack
import React, { Component } from "react"; import styled from "styled-components"; import { ChartType, EdgeType, NodeType, ResourceType } from "shared/types"; import Node from "./Node"; import Edge from "./Edge"; import InfoPanel from "./InfoPanel"; import ZoomPanel from "./ZoomPanel"; import SelectRegion from "./SelectRegion"; import _ from "lodash"; const zoomConstant = 0.01; const panConstant = 0.8; type PropsType = { components: ResourceType[]; isExpanded: boolean; setSidebar: (x: boolean) => void; currentChart: ChartType; // Handle revisions expansion for YAML wrapper showRevisions: boolean; }; type StateType = { nodes: NodeType[]; edges: EdgeType[]; activeIds: number[]; // IDs of all currently selected nodes originX: number | null; originY: number | null; cursorX: number | null; cursorY: number | null; deltaX: number | null; // Dragging bg x-displacement deltaY: number | null; // Dragging y-displacement panX: number | null; // Two-finger pan x-displacement panY: number | null; // Two-finger pan y-displacement anchorX: number | null; // Initial cursorX during region select anchorY: number | null; // Initial cursorY during region select nodeClickX: number | null; // Initial cursorX during node click (drag vs click) nodeClickY: number | null; // Initial cursorY during node click (drag vs click) dragBg: boolean; // Boolean to track if all nodes should move with mouse (bg drag) preventBgDrag: boolean; // Prevent bg drag when moving selected with mouse down relocateAllowed: boolean; // Suppress movement of selected when drawing select region scale: number; btnZooming: boolean; showKindLabels: boolean; isExpanded: boolean; currentNode: NodeType | null; currentEdge: EdgeType | null; openedNode: NodeType | null; suppressCloseNode: boolean; // Still click should close opened unless on a node suppressDisplay: boolean; // Ignore clicks + pan/zoom on InfoPanel or ButtonSection version?: number; // Track in localstorage for handling updates when unmounted }; // TODO: region-based unselect, shift-click, multi-region export default class GraphDisplay extends Component<PropsType, StateType> { state = { nodes: [] as NodeType[], edges: [] as EdgeType[], activeIds: [] as number[], originX: null as number | null, originY: null as number | null, cursorX: null as number | null, cursorY: null as number | null, deltaX: null as number | null, deltaY: null as number | null, panX: null as number | null, panY: null as number | null, anchorX: null as number | null, anchorY: null as number | null, nodeClickX: null as number | null, nodeClickY: null as number | null, dragBg: false, preventBgDrag: false, relocateAllowed: false, scale: 0.5, btnZooming: false, showKindLabels: true, isExpanded: false, currentNode: null as NodeType | null, currentEdge: null as EdgeType | null, openedNode: null as NodeType | null, suppressCloseNode: false, suppressDisplay: false, }; spaceRef: any = React.createRef(); getRandomIntBetweenRange = (min: number, max: number) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); }; // Handle graph from localstorage getChartGraph = () => { let { components, currentChart } = this.props; let graph = localStorage.getItem( `charts.${currentChart.name}-${currentChart.version}` ); let nodes = [] as NodeType[]; let edges = [] as EdgeType[]; if (!graph) { nodes = this.createNodes(components); edges = this.createEdges(components); this.setState({ nodes, edges }); } else { let storedState = JSON.parse( localStorage.getItem( `charts.${currentChart.name}-${currentChart.version}` ) ); this.setState(storedState); } }; componentDidMount() { // Initialize origin let height = this.spaceRef.offsetHeight; let width = this.spaceRef.offsetWidth; this.setState({ originX: Math.round(width / 2), originY: Math.round(height / 2), }); // Suppress trackpad gestures this.spaceRef.addEventListener("touchmove", (e: any) => e.preventDefault()); this.spaceRef.addEventListener("mousewheel", (e: any) => e.preventDefault() ); document.addEventListener("keydown", this.handleKeyDown); document.addEventListener("keyup", this.handleKeyUp); this.getChartGraph(); window.onbeforeunload = () => { this.storeChartGraph(); }; } // Live update on rollback/upgrade componentDidUpdate(prevProps: PropsType) { if (!_.isEqual(prevProps.currentChart, this.props.currentChart)) { this.storeChartGraph(prevProps); this.getChartGraph(); } } createNodes = (components: ResourceType[]) => { return components.map((c: ResourceType) => { switch (c.Kind) { case "ClusterRoleBinding": case "ClusterRole": case "RoleBinding": case "Role": return { id: c.ID, RawYAML: c.RawYAML, name: c.Name, kind: c.Kind, x: this.getRandomIntBetweenRange(-500, 0), y: this.getRandomIntBetweenRange(0, 250), w: 40, h: 40, }; case "Deployment": case "StatefulSet": case "Pod": case "ServiceAccount": return { id: c.ID, RawYAML: c.RawYAML, name: c.Name, kind: c.Kind, x: this.getRandomIntBetweenRange(0, 500), y: this.getRandomIntBetweenRange(0, 250), w: 40, h: 40, }; case "Service": case "Ingress": case "ServiceAccount": return { id: c.ID, RawYAML: c.RawYAML, name: c.Name, kind: c.Kind, x: this.getRandomIntBetweenRange(0, 500), y: this.getRandomIntBetweenRange(-250, 0), w: 40, h: 40, }; default: return { id: c.ID, RawYAML: c.RawYAML, name: c.Name, kind: c.Kind, x: this.getRandomIntBetweenRange(-400, 0), y: this.getRandomIntBetweenRange(-250, 0), w: 40, h: 40, }; } }); }; createEdges = (components: ResourceType[]) => { let edges = [] as EdgeType[]; components.map((c: ResourceType) => { c.Relations?.ControlRels?.map((rel: any) => { if (rel.Source == c.ID) { edges.push({ type: "ControlRel", source: rel.Source, target: rel.Target, }); } }); c.Relations?.LabelRels?.map((rel: any) => { if (rel.Source == c.ID) { edges.push({ type: "LabelRel", source: rel.Source, target: rel.Target, }); } }); c.Relations?.SpecRels?.map((rel: any) => { if (rel.Source == c.ID) { edges.push({ type: "SpecRel", source: rel.Source, target: rel.Target, }); } }); }); return edges; }; storeChartGraph = (props?: PropsType) => { let useProps = props || this.props; let { currentChart } = useProps; let graph = JSON.parse(JSON.stringify(this.state)); // Flush non-persistent data graph.activeIds = []; graph.currentNode = null; graph.currentEdge = null; graph.isExpanded = false; graph.openedNode = null; graph.suppressDisplay = false; graph.suppressCloseNode = false; localStorage.setItem( `charts.${currentChart.name}-${currentChart.version}`, JSON.stringify(graph) ); }; componentWillUnmount() { this.storeChartGraph(); this.spaceRef.removeEventListener("touchmove", (e: any) => e.preventDefault() ); this.spaceRef.removeEventListener("mousewheel", (e: any) => e.preventDefault() ); document.removeEventListener("keydown", this.handleKeyDown); document.removeEventListener("keyup", this.handleKeyUp); } // Handle shift key for multi-select handleKeyDown = (e: any) => { if (e.key === "Shift") { this.setState({ anchorX: this.state.cursorX, anchorY: this.state.cursorY, relocateAllowed: false, // Suppress jump when panning with mouse panX: null, panY: null, deltaX: null, deltaY: null, }); } }; handleKeyUp = (e: any) => { if (e.key === "Shift") { this.setState({ anchorX: null, anchorY: null, // Suppress jump when panning with mouse panX: null, panY: null, deltaX: null, deltaY: null, }); } }; handleClickNode = (clickedId: number) => { let { cursorX, cursorY } = this.state; // Store position for distinguishing click vs drag on release this.setState({ nodeClickX: cursorX, nodeClickY: cursorY, suppressCloseNode: true, }); // Push to activeIds if not already present let holding = this.state.activeIds; if (!holding.includes(clickedId)) { holding.push(clickedId); } // Track and store offset to grab node from anywhere (must store) this.state.nodes.forEach((node: NodeType) => { if (this.state.activeIds.includes(node.id)) { node.toCursorX = node.x - cursorX; node.toCursorY = node.y - cursorY; } }); this.setState({ activeIds: holding, preventBgDrag: true, relocateAllowed: true, }); }; handleReleaseNode = (node: NodeType) => { let { cursorX, cursorY, nodeClickX, nodeClickY } = this.state; this.setState({ activeIds: [], preventBgDrag: false }); // Distinguish node click vs drag (can't use onClick since drag counts) if (cursorX === nodeClickX && cursorY === nodeClickY) { this.setState({ openedNode: node }); } }; handleMouseDown = () => { let { cursorX, cursorY } = this.state; // Store position for distinguishing click vs drag on release this.setState({ nodeClickX: cursorX, nodeClickY: cursorY }); this.setState({ dragBg: true, // Suppress drifting on repeated click deltaX: null, deltaY: null, panX: null, panY: null, scale: 1, }); }; handleMouseUp = () => { let { cursorX, nodeClickX, cursorY, nodeClickY, suppressCloseNode, } = this.state; this.setState({ dragBg: false, activeIds: [] }); // Distinguish bg click vs drag for setting closing opened node if ( !suppressCloseNode && cursorX === nodeClickX && cursorY === nodeClickY ) { this.setState({ openedNode: null }); } else if (this.state.suppressCloseNode) { this.setState({ suppressCloseNode: false }); } }; handleMouseMove = (e: any) => { let { originX, originY, dragBg, preventBgDrag, scale, panX, panY, anchorX, anchorY, nodes, activeIds, relocateAllowed, } = this.state; // Suppress navigation gestures if (scale !== 1 || panX !== 0 || panY !== 0) { this.setState({ scale: 1, panX: 0, panY: 0 }); } // Update origin-centered cursor coordinates let bounds = this.spaceRef.getBoundingClientRect(); let cursorX = e.clientX - bounds.left - originX; let cursorY = -(e.clientY - bounds.top - originY); this.setState({ cursorX, cursorY }); // Track delta for dragging background if (dragBg && !preventBgDrag) { this.setState({ deltaX: e.movementX, deltaY: e.movementY }); } // Check if within select region if (anchorX && anchorY) { nodes.forEach((node: NodeType) => { if ( node.x > Math.min(anchorX, cursorX) && node.x < Math.max(anchorX, cursorX) && node.y > Math.min(anchorY, cursorY) && node.y < Math.max(anchorY, cursorY) ) { activeIds.push(node.id); this.setState({ activeIds }); } }); } }; // Handle pan XOR zoom (two-finger gestures count as onWheel) handleWheel = (e: any) => { this.setState({ btnZooming: false }); // Prevent nav gestures if mouse is over InfoPanel or ButtonSection if (!this.state.suppressDisplay) { // Pinch/zoom sets e.ctrlKey to true if (e.ctrlKey) { // Clip deltaY for extreme mousewheel values let deltaY = e.deltaY >= 0 ? Math.min(40, e.deltaY) : Math.max(-40, e.deltaY); let scale = 1; scale -= deltaY * zoomConstant; this.setState({ scale, panX: 0, panY: 0 }); } else { this.setState({ panX: e.deltaX, panY: e.deltaY, scale: 1 }); } } }; btnZoomIn = () => { this.setState({ scale: 1.24, btnZooming: true }); }; btnZoomOut = () => { this.setState({ scale: 0.76, btnZooming: true }); }; toggleExpanded = () => { this.setState({ isExpanded: !this.state.isExpanded }, () => { this.props.setSidebar(!this.state.isExpanded); // Update origin on expand/collapse let height = this.spaceRef.offsetHeight; let width = this.spaceRef.offsetWidth; let nudge = 0; if (!this.state.isExpanded) { nudge = 100; } this.setState({ originX: Math.round(width / 2) - nudge, originY: Math.round(height / 2), }); }); }; // Pass origin to node for offset renderNodes = () => { let { activeIds, originX, originY, cursorX, cursorY, scale, panX, panY, anchorX, anchorY, relocateAllowed, } = this.state; let minX = 0; let maxX = 0; let minY = 0; let maxY = 0; this.state.nodes.map((node: NodeType, i: number) => { if (node.x < minX) minX = node.x < minX ? node.x : minX; maxX = node.x > maxX ? node.x : maxX; minY = node.y < minY ? node.y : minY; maxY = node.y > maxY ? node.y : maxY; }); let midX = (minX + maxX) / 2; let midY = (minY + maxY) / 2; return this.state.nodes.map((node: NodeType, i: number) => { // Update position if not highlighting and active if ( activeIds.includes(node.id) && relocateAllowed && !anchorX && !anchorY ) { node.x = cursorX + node.toCursorX; node.y = cursorY + node.toCursorY; } // Apply movement from dragging background if (this.state.dragBg && !this.state.preventBgDrag) { node.x += this.state.deltaX; node.y -= this.state.deltaY; } // Apply cursor-centered zoom if (this.state.scale !== 1) { if (!this.state.btnZooming) { node.x = cursorX + scale * (node.x - cursorX); node.y = cursorY + scale * (node.y - cursorY); } else { node.x = midX + scale * (node.x - midX); node.y = midY + scale * (node.y - midY); } } // Apply pan if (this.state.panX !== 0 || this.state.panY !== 0) { node.x -= panConstant * panX; node.y += panConstant * panY; } return ( <Node key={i} node={node} originX={originX} originY={originY} nodeMouseDown={() => this.handleClickNode(node.id)} nodeMouseUp={() => this.handleReleaseNode(node)} isActive={activeIds.includes(node.id)} showKindLabels={this.state.showKindLabels} isOpen={node === this.state.openedNode} // Parameterized to allow setting to null setCurrentNode={(node: NodeType) => { this.setState({ currentNode: node }); }} /> ); }); }; renderEdges = () => { return this.state.edges.map((edge: EdgeType, i: number) => { return ( <Edge key={i} originX={this.state.originX} originY={this.state.originY} x1={this.state.nodes[edge.source].x} y1={this.state.nodes[edge.source].y} x2={this.state.nodes[edge.target].x} y2={this.state.nodes[edge.target].y} edge={edge} setCurrentEdge={(edge: EdgeType) => this.setState({ currentEdge: edge }) } /> ); }); }; renderSelectRegion = () => { if (this.state.anchorX && this.state.anchorY) { return ( <SelectRegion anchorX={this.state.anchorX} anchorY={this.state.anchorY} originX={this.state.originX} originY={this.state.originY} cursorX={this.state.cursorX} cursorY={this.state.cursorY} /> ); } }; render() { return ( <StyledGraphDisplay isExpanded={this.state.isExpanded} ref={(element) => (this.spaceRef = element)} onMouseMove={this.handleMouseMove} onMouseDown={this.state.suppressDisplay ? null : this.handleMouseDown} onMouseUp={this.state.suppressDisplay ? null : this.handleMouseUp} onWheel={this.handleWheel} > {this.renderNodes()} {this.renderEdges()} {this.renderSelectRegion()} <ButtonSection onMouseEnter={() => this.setState({ suppressDisplay: true })} onMouseLeave={() => this.setState({ suppressDisplay: false })} > <ToggleLabel onClick={() => this.setState({ showKindLabels: !this.state.showKindLabels }) } > <Checkbox checked={this.state.showKindLabels}> <i className="material-icons">done</i> </Checkbox> Show Type </ToggleLabel> {/* <ExpandButton onClick={this.toggleExpanded}> <i className="material-icons"> {this.state.isExpanded ? "close_fullscreen" : "open_in_full"} </i> </ExpandButton> */} </ButtonSection> <InfoPanel setSuppressDisplay={(x: boolean) => this.setState({ suppressDisplay: x }) } currentNode={this.state.currentNode} currentEdge={this.state.currentEdge} openedNode={this.state.openedNode} // InfoPanel won't trigger onMouseLeave for unsuppressing if close is clicked closeNode={() => this.setState({ openedNode: null, suppressDisplay: false }) } // For YAML wrapper to trigger resize isExpanded={this.state.isExpanded} showRevisions={this.props.showRevisions} /> <ZoomPanel btnZoomIn={this.btnZoomIn} btnZoomOut={this.btnZoomOut} /> </StyledGraphDisplay> ); } } const Checkbox = styled.div` width: 16px; height: 16px; border: 1px solid #ffffff55; margin: 0px 8px 0px 3px; border-radius: 3px; background: ${(props: { checked: boolean }) => props.checked ? "#ffffff22" : ""}; display: flex; align-items: center; justify-content: center; color: #ffffff; > i { font-size: 12px; padding-left: 0px; display: ${(props: { checked: boolean }) => (props.checked ? "" : "none")}; } `; const ToggleLabel = styled.div` font: 12px "Work Sans"; color: #ffffff; position: relative; height: 24px; display: flex; align-items: center; justify-content: space-between; border-radius: 3px; padding-right: 5px; cursor: pointer; border: 1px solid #ffffff55; :hover { background: #ffffff22; > div { background: #ffffff22; } } `; const ButtonSection = styled.div` position: absolute; top: 15px; right: 15px; display: flex; align-items: center; z-index: 999; cursor: pointer; `; const ExpandButton = styled.div` width: 24px; height: 24px; cursor: pointer; margin-left: 10px; display: flex; justify-content: center; align-items: center; border-radius: 3px; border: 1px solid #ffffff55; :hover { background: #ffffff44; } > i { font-size: 14px; } `; const StyledGraphDisplay = styled.div` overflow: hidden; cursor: move; width: ${(props: { isExpanded: boolean }) => props.isExpanded ? "100vw" : "100%"}; height: ${(props: { isExpanded: boolean }) => props.isExpanded ? "100vh" : "100%"}; background: #202227; position: ${(props: { isExpanded: boolean }) => props.isExpanded ? "fixed" : "relative"}; top: ${(props: { isExpanded: boolean }) => (props.isExpanded ? "-25px" : "")}; right: ${(props: { isExpanded: boolean }) => props.isExpanded ? "-25px" : ""}; `;
the_stack
import { configurationValue } from "@atomist/automation-client/lib/configuration"; import { HandlerContext } from "@atomist/automation-client/lib/HandlerContext"; import { failure, HandlerResult, Success } from "@atomist/automation-client/lib/HandlerResult"; import { RemoteRepoRef } from "@atomist/automation-client/lib/operations/common/RepoId"; import { GitProject } from "@atomist/automation-client/lib/project/git/GitProject"; import { logger } from "@atomist/automation-client/lib/util/logger"; import * as _ from "lodash"; import * as path from "path"; import { AddressChannels } from "../../api/context/addressChannels"; import { createSkillContext } from "../../api/context/skillContext"; import { ExecuteGoalResult, isFailure } from "../../api/goal/ExecuteGoalResult"; import { Goal } from "../../api/goal/Goal"; import { ExecuteGoal, GoalInvocation, GoalProjectListenerEvent, GoalProjectListenerRegistration, } from "../../api/goal/GoalInvocation"; import { ReportProgress } from "../../api/goal/progress/ReportProgress"; import { SdmGoalEvent } from "../../api/goal/SdmGoalEvent"; import { GoalImplementation } from "../../api/goal/support/GoalImplementationMapper"; import { GoalExecutionListener, GoalExecutionListenerInvocation } from "../../api/listener/GoalStatusListener"; import { SoftwareDeliveryMachineConfiguration } from "../../api/machine/SoftwareDeliveryMachineOptions"; import { AnyPush } from "../../api/mapping/support/commonPushTests"; import { InterpretLog } from "../../spi/log/InterpretedLog"; import { ProgressLog } from "../../spi/log/ProgressLog"; import { isLazyProjectLoader, LazyProject } from "../../spi/project/LazyProjectLoader"; import { ProjectLoader } from "../../spi/project/ProjectLoader"; import { SdmGoalState } from "../../typings/types"; import { format } from "../log/format"; import { WriteToAllProgressLog } from "../log/WriteToAllProgressLog"; import { spawnLog } from "../misc/child_process"; import { toToken } from "../misc/credentials/toToken"; import { reportFailureInterpretation } from "../misc/reportFailureInterpretation"; import { serializeResult } from "../misc/result"; import { ProjectListenerInvokingProjectLoader } from "../project/ProjectListenerInvokingProjectLoader"; import { mockGoalExecutor } from "./mock"; import { descriptionFromState, updateGoal } from "./storeGoals"; class GoalExecutionError extends Error { public readonly where: string; public readonly result?: ExecuteGoalResult; public readonly cause?: Error; constructor(params: { where: string; result?: ExecuteGoalResult; cause?: Error }) { super("Failure in " + params.where); Object.setPrototypeOf(this, new.target.prototype); this.where = params.where; this.result = params.result; this.cause = params.cause; } get description(): string { const resultDescription = this.result ? ` Result code ${this.result.code} ${this.result.message}` : ""; const causeDescription = this.cause ? ` Caused by: ${this.cause.message}` : ""; return `Failure in ${this.where}:${resultDescription}${causeDescription}`; } } /** * Central function to execute a goal with progress logging */ export async function executeGoal( rules: { projectLoader: ProjectLoader; goalExecutionListeners: GoalExecutionListener[] }, implementation: GoalImplementation, gi: GoalInvocation, ): Promise<ExecuteGoalResult> { const { goal, goalEvent, addressChannels, progressLog, id, context, credentials, configuration, preferences } = gi; const { progressReporter, logInterpreter, projectListeners } = implementation; const implementationName = goalEvent.fulfillment.name; if (!!progressReporter) { gi.progressLog = new WriteToAllProgressLog( goalEvent.name, gi.progressLog, new ProgressReportingProgressLog(progressReporter, goalEvent, gi.context), ); } const push = goalEvent.push; logger.info(`Starting goal '%s' on '%s/%s/%s'`, goalEvent.uniqueName, push.repo.owner, push.repo.name, push.branch); async function notifyGoalExecutionListeners( sge: SdmGoalEvent, result?: ExecuteGoalResult, error?: Error, ): Promise<void> { const inProcessGoalExecutionListenerInvocation: GoalExecutionListenerInvocation = { id, context, addressChannels, configuration, preferences, credentials, goal, goalEvent: sge, error, result, skill: createSkillContext(context), }; await Promise.all( rules.goalExecutionListeners.map(gel => { try { return gel(inProcessGoalExecutionListenerInvocation); } catch (e) { logger.warn(`GoalExecutionListener failed: ${e.message}`); logger.debug(e); return undefined; } }), ); } const inProcessGoalEvent = await markGoalInProcess({ ctx: context, goalEvent, goal, progressLogUrl: progressLog.url, }); await notifyGoalExecutionListeners(inProcessGoalEvent); try { const goalInvocation = prepareGoalInvocation(gi, projectListeners); // execute pre hook const preHookResult: ExecuteGoalResult = (await executeHook(rules, goalInvocation, inProcessGoalEvent, "pre").catch(async err => { throw new GoalExecutionError({ where: "executing pre-goal hook", cause: err }); })) || Success; if (isFailure(preHookResult)) { throw new GoalExecutionError({ where: "executing pre-goal hook", result: preHookResult }); } // execute the actual goal const goalResult: ExecuteGoalResult = (await prepareGoalExecutor( implementation, inProcessGoalEvent, configuration, )(goalInvocation).catch(async err => { throw new GoalExecutionError({ where: "executing goal", cause: err }); })) || Success; if (isFailure(goalResult)) { throw new GoalExecutionError({ where: "executing goal", result: goalResult }); } // execute post hook const postHookResult: ExecuteGoalResult = (await executeHook(rules, goalInvocation, inProcessGoalEvent, "post").catch(async err => { throw new GoalExecutionError({ where: "executing post-goal hook", cause: err }); })) || Success; if (isFailure(postHookResult)) { throw new GoalExecutionError({ where: "executing post-goal hooks", result: postHookResult }); } const result = { ...preHookResult, ...goalResult, ...postHookResult, }; await notifyGoalExecutionListeners( { ...inProcessGoalEvent, state: SdmGoalState.success, }, result, ); logger.info("Goal '%s' completed with: %j", goalEvent.uniqueName, result); await markStatus({ context, goalEvent, goal, result, progressLogUrl: progressLog.url }); return { ...result, code: 0 }; } catch (err) { logger.warn("Error executing goal '%s': %s", goalEvent.uniqueName, err.message); const result = handleGitRefErrors({ code: 1, ...(err.result || {}) }, err); await notifyGoalExecutionListeners( { ...inProcessGoalEvent, state: result.state || SdmGoalState.failure, }, result, err, ); await reportGoalError( { goal, implementationName, addressChannels, progressLog, id, logInterpreter, }, err, ); await markStatus({ context, goalEvent, goal, result, error: err, progressLogUrl: progressLog.url, }); return failure(err); } } export async function executeHook( rules: { projectLoader: ProjectLoader }, goalInvocation: GoalInvocation, sdmGoal: SdmGoalEvent, stage: "post" | "pre", ): Promise<HandlerResult> { const hook = goalToHookFile(sdmGoal, stage); // Check configuration to see if hooks should be skipped if (!configurationValue<boolean>("sdm.goal.hooks", false)) { return Success; } const { projectLoader } = rules; const { credentials, id, context, progressLog } = goalInvocation; return projectLoader.doWithProject( { credentials, id, context, readOnly: true, cloneOptions: { detachHead: true }, }, async p => { if (await p.hasFile(path.join(".atomist", "hooks", hook))) { progressLog.write("/--"); progressLog.write(`Invoking goal hook: ${hook}`); const opts = { cwd: path.join(p.baseDir, ".atomist", "hooks"), env: { ...process.env, GITHUB_TOKEN: toToken(credentials), ATOMIST_WORKSPACE: context.workspaceId, ATOMIST_CORRELATION_ID: context.correlationId, ATOMIST_REPO: sdmGoal.push.repo.name, ATOMIST_OWNER: sdmGoal.push.repo.owner, }, log: progressLog, }; const cmd = path.join(p.baseDir, ".atomist", "hooks", hook); let result: HandlerResult = await spawnLog(cmd, [], opts); if (!result) { result = Success; } progressLog.write(`Result: ${serializeResult(result)}`); progressLog.write("\\--"); await progressLog.flush(); return result; } else { return Success; } }, ); } function goalToHookFile(sdmGoal: SdmGoalEvent, prefix: string): string { return `${prefix}-${sdmGoal.environment.toLocaleLowerCase().slice(2)}-${sdmGoal.name .toLocaleLowerCase() .replace(" ", "_")}`; } export function markStatus(parameters: { context: HandlerContext; goalEvent: SdmGoalEvent; goal: Goal; result: ExecuteGoalResult; error?: Error; progressLogUrl: string; }): Promise<void> { const { context, goalEvent, goal, result, error, progressLogUrl } = parameters; let newState = SdmGoalState.success; if (result.state) { newState = result.state; } else if (result.code !== 0) { newState = SdmGoalState.failure; } else if (goal.definition.approvalRequired) { newState = SdmGoalState.waiting_for_approval; } return updateGoal(context, goalEvent, { url: progressLogUrl, externalUrls: result.externalUrls || [], state: newState, phase: result.phase ? result.phase : goalEvent.phase, description: result.description ? result.description : descriptionFromState(goal, newState, goalEvent), error, data: result.data ? result.data : goalEvent.data, }); } function handleGitRefErrors(result: ExecuteGoalResult, error: Error & any): ExecuteGoalResult { if (!!error?.cause?.stderr) { const err = error?.cause?.stderr; if (/Remote branch .* not found/.test(err)) { result.code = 0; result.state = SdmGoalState.canceled; result.phase = "branch not found"; } else if (/reference is not a tree/.test(err)) { result.code = 0; result.state = SdmGoalState.canceled; result.phase = "sha not found"; } } return result; } async function markGoalInProcess(parameters: { ctx: HandlerContext; goalEvent: SdmGoalEvent; goal: Goal; progressLogUrl: string; }): Promise<SdmGoalEvent> { const { ctx, goalEvent, goal, progressLogUrl } = parameters; goalEvent.state = SdmGoalState.in_process; goalEvent.description = descriptionFromState(goal, SdmGoalState.in_process, goalEvent); goalEvent.url = progressLogUrl; await updateGoal(ctx, goalEvent, { url: progressLogUrl, description: descriptionFromState(goal, SdmGoalState.in_process, goalEvent), state: SdmGoalState.in_process, }); return goalEvent; } /** * Report an error executing a goal and present a retry button * @return {Promise<void>} */ async function reportGoalError( parameters: { goal: Goal; implementationName: string; addressChannels: AddressChannels; progressLog: ProgressLog; id: RemoteRepoRef; logInterpreter: InterpretLog; }, err: GoalExecutionError, ): Promise<void> { const { implementationName, addressChannels, progressLog, id, logInterpreter } = parameters; if (err.cause) { logger.warn(err.cause.stack); progressLog.write(err.cause.stack); } else if (err.result && (err.result as any).error) { logger.warn((err.result as any).error.stack); progressLog.write((err.result as any).error.stack); } else { logger.warn(err.stack); } progressLog.write("Error: " + (err.description || err.message) + "\n"); const interpretation = logInterpreter(progressLog.log); // The executor might have information about the failure; report it in the channels if (interpretation) { if (!interpretation.doNotReportToUser) { await reportFailureInterpretation( implementationName, interpretation, { url: progressLog.url, log: progressLog.log }, id, addressChannels, ); } } } export function prepareGoalExecutor( gi: GoalImplementation, sdmGoal: SdmGoalEvent, configuration: SoftwareDeliveryMachineConfiguration, ): ExecuteGoal { const mge = mockGoalExecutor(gi.goal, sdmGoal, configuration); if (mge) { return mge; } else { return gi.goalExecutor; } } export function prepareGoalInvocation( gi: GoalInvocation, listeners: GoalProjectListenerRegistration | GoalProjectListenerRegistration[], ): GoalInvocation { let hs: GoalProjectListenerRegistration[] = listeners ? Array.isArray(listeners) ? listeners : [listeners] : ([] as GoalProjectListenerRegistration[]); if (isLazyProjectLoader(gi.configuration.sdm.projectLoader)) { // Register the materializing listener for LazyProject instances of those need to // get materialized before using in goal implementations const projectMaterializer = { name: "clone project", pushTest: AnyPush, events: [GoalProjectListenerEvent.before], listener: async (p: GitProject & LazyProject) => { if (!p.materialized()) { // Trigger project materialization await p.materialize(); } return { code: 0 }; }, }; hs = [projectMaterializer, ...hs]; } if (hs.length === 0) { return gi; } const configuration = _.cloneDeep(gi.configuration); configuration.sdm.projectLoader = new ProjectListenerInvokingProjectLoader(gi, hs); const newGi: GoalInvocation = { ...gi, configuration, }; return newGi; } /** * ProgressLog implementation that uses the configured ReportProgress * instance to report goal execution updates. */ class ProgressReportingProgressLog implements ProgressLog { public log: string; public readonly name: string; public url: string; constructor( private readonly progressReporter: ReportProgress, private readonly sdmGoal: SdmGoalEvent, private readonly context: HandlerContext, ) { this.name = sdmGoal.name; } public async close(): Promise<void> { return; } public async flush(): Promise<void> { return; } public async isAvailable(): Promise<boolean> { return true; } public write(msg: string, ...args: string[]): void { const progress = this.progressReporter(format(msg, ...args), this.sdmGoal); if (progress && progress.phase) { if (this.sdmGoal.phase !== progress.phase) { this.sdmGoal.phase = progress.phase; updateGoal(this.context, this.sdmGoal, { state: this.sdmGoal.state, phase: progress.phase, description: this.sdmGoal.description, url: this.sdmGoal.url, }) .then(() => { // Intentionally empty }) .catch(err => { logger.debug(`Error occurred reporting progress: %s`, err.message); }); } } } }
the_stack
'use strict'; import * as assert from 'assert'; import { INormalizedVersion, IParsedVersion, IReducedExtensionDescription, isValidExtensionVersion, isValidVersion, isValidVersionStr, normalizeVersion, parseVersion } from 'vs/platform/extensions/node/extensionValidator'; suite('Extension Version Validator', () => { test('isValidVersionStr', () => { assert.equal(isValidVersionStr('0.10.0-dev'), true); assert.equal(isValidVersionStr('0.10.0'), true); assert.equal(isValidVersionStr('0.10.1'), true); assert.equal(isValidVersionStr('0.10.100'), true); assert.equal(isValidVersionStr('0.11.0'), true); assert.equal(isValidVersionStr('x.x.x'), true); assert.equal(isValidVersionStr('0.x.x'), true); assert.equal(isValidVersionStr('0.10.0'), true); assert.equal(isValidVersionStr('0.10.x'), true); assert.equal(isValidVersionStr('^0.10.0'), true); assert.equal(isValidVersionStr('*'), true); assert.equal(isValidVersionStr('0.x.x.x'), false); assert.equal(isValidVersionStr('0.10'), false); assert.equal(isValidVersionStr('0.10.'), false); }); test('parseVersion', () => { function assertParseVersion(version: string, hasCaret: boolean, hasGreaterEquals: boolean, majorBase: number, majorMustEqual: boolean, minorBase: number, minorMustEqual: boolean, patchBase: number, patchMustEqual: boolean, preRelease: string): void { const actual = parseVersion(version); const expected: IParsedVersion = { hasCaret, hasGreaterEquals, majorBase, majorMustEqual, minorBase, minorMustEqual, patchBase, patchMustEqual, preRelease }; assert.deepEqual(actual, expected, 'parseVersion for ' + version); } assertParseVersion('0.10.0-dev', false, false, 0, true, 10, true, 0, true, '-dev'); assertParseVersion('0.10.0', false, false, 0, true, 10, true, 0, true, null); assertParseVersion('0.10.1', false, false, 0, true, 10, true, 1, true, null); assertParseVersion('0.10.100', false, false, 0, true, 10, true, 100, true, null); assertParseVersion('0.11.0', false, false, 0, true, 11, true, 0, true, null); assertParseVersion('x.x.x', false, false, 0, false, 0, false, 0, false, null); assertParseVersion('0.x.x', false, false, 0, true, 0, false, 0, false, null); assertParseVersion('0.10.x', false, false, 0, true, 10, true, 0, false, null); assertParseVersion('^0.10.0', true, false, 0, true, 10, true, 0, true, null); assertParseVersion('^0.10.2', true, false, 0, true, 10, true, 2, true, null); assertParseVersion('^1.10.2', true, false, 1, true, 10, true, 2, true, null); assertParseVersion('*', false, false, 0, false, 0, false, 0, false, null); assertParseVersion('>=0.0.1', false, true, 0, true, 0, true, 1, true, null); assertParseVersion('>=2.4.3', false, true, 2, true, 4, true, 3, true, null); }); test('normalizeVersion', () => { function assertNormalizeVersion(version: string, majorBase: number, majorMustEqual: boolean, minorBase: number, minorMustEqual: boolean, patchBase: number, patchMustEqual: boolean, isMinimum: boolean): void { const actual = normalizeVersion(parseVersion(version)); const expected: INormalizedVersion = { majorBase, majorMustEqual, minorBase, minorMustEqual, patchBase, patchMustEqual, isMinimum }; assert.deepEqual(actual, expected, 'parseVersion for ' + version); } assertNormalizeVersion('0.10.0-dev', 0, true, 10, true, 0, true, false); assertNormalizeVersion('0.10.0', 0, true, 10, true, 0, true, false); assertNormalizeVersion('0.10.1', 0, true, 10, true, 1, true, false); assertNormalizeVersion('0.10.100', 0, true, 10, true, 100, true, false); assertNormalizeVersion('0.11.0', 0, true, 11, true, 0, true, false); assertNormalizeVersion('x.x.x', 0, false, 0, false, 0, false, false); assertNormalizeVersion('0.x.x', 0, true, 0, false, 0, false, false); assertNormalizeVersion('0.10.x', 0, true, 10, true, 0, false, false); assertNormalizeVersion('^0.10.0', 0, true, 10, true, 0, false, false); assertNormalizeVersion('^0.10.2', 0, true, 10, true, 2, false, false); assertNormalizeVersion('^1.10.2', 1, true, 10, false, 2, false, false); assertNormalizeVersion('*', 0, false, 0, false, 0, false, false); assertNormalizeVersion('>=0.0.1', 0, true, 0, true, 1, true, true); assertNormalizeVersion('>=2.4.3', 2, true, 4, true, 3, true, true); }); test('isValidVersion', () => { function testIsValidVersion(version: string, desiredVersion: string, expectedResult: boolean): void { let actual = isValidVersion(version, desiredVersion); assert.equal(actual, expectedResult, 'extension - vscode: ' + version + ', desiredVersion: ' + desiredVersion + ' should be ' + expectedResult); } testIsValidVersion('0.10.0-dev', 'x.x.x', true); testIsValidVersion('0.10.0-dev', '0.x.x', true); testIsValidVersion('0.10.0-dev', '0.10.0', true); testIsValidVersion('0.10.0-dev', '0.10.2', false); testIsValidVersion('0.10.0-dev', '^0.10.2', false); testIsValidVersion('0.10.0-dev', '0.10.x', true); testIsValidVersion('0.10.0-dev', '^0.10.0', true); testIsValidVersion('0.10.0-dev', '*', true); testIsValidVersion('0.10.0-dev', '>=0.0.1', true); testIsValidVersion('0.10.0-dev', '>=0.0.10', true); testIsValidVersion('0.10.0-dev', '>=0.10.0', true); testIsValidVersion('0.10.0-dev', '>=0.10.1', false); testIsValidVersion('0.10.0-dev', '>=1.0.0', false); testIsValidVersion('0.10.0', 'x.x.x', true); testIsValidVersion('0.10.0', '0.x.x', true); testIsValidVersion('0.10.0', '0.10.0', true); testIsValidVersion('0.10.0', '0.10.2', false); testIsValidVersion('0.10.0', '^0.10.2', false); testIsValidVersion('0.10.0', '0.10.x', true); testIsValidVersion('0.10.0', '^0.10.0', true); testIsValidVersion('0.10.0', '*', true); testIsValidVersion('0.10.1', 'x.x.x', true); testIsValidVersion('0.10.1', '0.x.x', true); testIsValidVersion('0.10.1', '0.10.0', false); testIsValidVersion('0.10.1', '0.10.2', false); testIsValidVersion('0.10.1', '^0.10.2', false); testIsValidVersion('0.10.1', '0.10.x', true); testIsValidVersion('0.10.1', '^0.10.0', true); testIsValidVersion('0.10.1', '*', true); testIsValidVersion('0.10.100', 'x.x.x', true); testIsValidVersion('0.10.100', '0.x.x', true); testIsValidVersion('0.10.100', '0.10.0', false); testIsValidVersion('0.10.100', '0.10.2', false); testIsValidVersion('0.10.100', '^0.10.2', true); testIsValidVersion('0.10.100', '0.10.x', true); testIsValidVersion('0.10.100', '^0.10.0', true); testIsValidVersion('0.10.100', '*', true); testIsValidVersion('0.11.0', 'x.x.x', true); testIsValidVersion('0.11.0', '0.x.x', true); testIsValidVersion('0.11.0', '0.10.0', false); testIsValidVersion('0.11.0', '0.10.2', false); testIsValidVersion('0.11.0', '^0.10.2', false); testIsValidVersion('0.11.0', '0.10.x', false); testIsValidVersion('0.11.0', '^0.10.0', false); testIsValidVersion('0.11.0', '*', true); // Anything < 1.0.0 is compatible testIsValidVersion('1.0.0', 'x.x.x', true); testIsValidVersion('1.0.0', '0.x.x', true); testIsValidVersion('1.0.0', '0.10.0', false); testIsValidVersion('1.0.0', '0.10.2', false); testIsValidVersion('1.0.0', '^0.10.2', true); testIsValidVersion('1.0.0', '0.10.x', true); testIsValidVersion('1.0.0', '^0.10.0', true); testIsValidVersion('1.0.0', '1.0.0', true); testIsValidVersion('1.0.0', '^1.0.0', true); testIsValidVersion('1.0.0', '^2.0.0', false); testIsValidVersion('1.0.0', '*', true); testIsValidVersion('1.0.0', '>=0.0.1', true); testIsValidVersion('1.0.0', '>=0.0.10', true); testIsValidVersion('1.0.0', '>=0.10.0', true); testIsValidVersion('1.0.0', '>=0.10.1', true); testIsValidVersion('1.0.0', '>=1.0.0', true); testIsValidVersion('1.0.0', '>=1.1.0', false); testIsValidVersion('1.0.0', '>=1.0.1', false); testIsValidVersion('1.0.0', '>=2.0.0', false); testIsValidVersion('1.0.100', 'x.x.x', true); testIsValidVersion('1.0.100', '0.x.x', true); testIsValidVersion('1.0.100', '0.10.0', false); testIsValidVersion('1.0.100', '0.10.2', false); testIsValidVersion('1.0.100', '^0.10.2', true); testIsValidVersion('1.0.100', '0.10.x', true); testIsValidVersion('1.0.100', '^0.10.0', true); testIsValidVersion('1.0.100', '1.0.0', false); testIsValidVersion('1.0.100', '^1.0.0', true); testIsValidVersion('1.0.100', '^1.0.1', true); testIsValidVersion('1.0.100', '^2.0.0', false); testIsValidVersion('1.0.100', '*', true); testIsValidVersion('1.100.0', 'x.x.x', true); testIsValidVersion('1.100.0', '0.x.x', true); testIsValidVersion('1.100.0', '0.10.0', false); testIsValidVersion('1.100.0', '0.10.2', false); testIsValidVersion('1.100.0', '^0.10.2', true); testIsValidVersion('1.100.0', '0.10.x', true); testIsValidVersion('1.100.0', '^0.10.0', true); testIsValidVersion('1.100.0', '1.0.0', false); testIsValidVersion('1.100.0', '^1.0.0', true); testIsValidVersion('1.100.0', '^1.1.0', true); testIsValidVersion('1.100.0', '^1.100.0', true); testIsValidVersion('1.100.0', '^2.0.0', false); testIsValidVersion('1.100.0', '*', true); testIsValidVersion('1.100.0', '>=1.99.0', true); testIsValidVersion('1.100.0', '>=1.100.0', true); testIsValidVersion('1.100.0', '>=1.101.0', false); testIsValidVersion('2.0.0', 'x.x.x', true); testIsValidVersion('2.0.0', '0.x.x', false); testIsValidVersion('2.0.0', '0.10.0', false); testIsValidVersion('2.0.0', '0.10.2', false); testIsValidVersion('2.0.0', '^0.10.2', false); testIsValidVersion('2.0.0', '0.10.x', false); testIsValidVersion('2.0.0', '^0.10.0', false); testIsValidVersion('2.0.0', '1.0.0', false); testIsValidVersion('2.0.0', '^1.0.0', false); testIsValidVersion('2.0.0', '^1.1.0', false); testIsValidVersion('2.0.0', '^1.100.0', false); testIsValidVersion('2.0.0', '^2.0.0', true); testIsValidVersion('2.0.0', '*', true); }); test('isValidExtensionVersion', () => { function testExtensionVersion(version: string, desiredVersion: string, isBuiltin: boolean, hasMain: boolean, expectedResult: boolean): void { let desc: IReducedExtensionDescription = { isBuiltin: isBuiltin, engines: { vscode: desiredVersion }, main: hasMain ? 'something' : undefined }; let reasons: string[] = []; let actual = isValidExtensionVersion(version, desc, reasons); assert.equal(actual, expectedResult, 'version: ' + version + ', desiredVersion: ' + desiredVersion + ', desc: ' + JSON.stringify(desc) + ', reasons: ' + JSON.stringify(reasons)); } function testIsInvalidExtensionVersion(version: string, desiredVersion: string, isBuiltin: boolean, hasMain: boolean): void { testExtensionVersion(version, desiredVersion, isBuiltin, hasMain, false); } function testIsValidExtensionVersion(version: string, desiredVersion: string, isBuiltin: boolean, hasMain: boolean): void { testExtensionVersion(version, desiredVersion, isBuiltin, hasMain, true); } function testIsValidVersion(version: string, desiredVersion: string, expectedResult: boolean): void { testExtensionVersion(version, desiredVersion, false, true, expectedResult); } // builtin are allowed to use * or x.x.x testIsValidExtensionVersion('0.10.0-dev', '*', true, true); testIsValidExtensionVersion('0.10.0-dev', 'x.x.x', true, true); testIsValidExtensionVersion('0.10.0-dev', '0.x.x', true, true); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', true, true); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', true, true); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', true, true); testIsValidExtensionVersion('0.10.0-dev', '*', true, false); testIsValidExtensionVersion('0.10.0-dev', 'x.x.x', true, false); testIsValidExtensionVersion('0.10.0-dev', '0.x.x', true, false); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', true, false); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', true, false); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', true, false); // normal extensions are allowed to use * or x.x.x only if they have no main testIsInvalidExtensionVersion('0.10.0-dev', '*', false, true); testIsInvalidExtensionVersion('0.10.0-dev', 'x.x.x', false, true); testIsInvalidExtensionVersion('0.10.0-dev', '0.x.x', false, true); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', false, true); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', false, true); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', false, true); testIsValidExtensionVersion('0.10.0-dev', '*', false, false); testIsValidExtensionVersion('0.10.0-dev', 'x.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', false, false); // extensions without "main" get no version check testIsValidExtensionVersion('0.10.0-dev', '>=0.9.1-pre.1', false, false); testIsValidExtensionVersion('0.10.0-dev', '*', false, false); testIsValidExtensionVersion('0.10.0-dev', 'x.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '*', false, false); testIsValidExtensionVersion('0.10.0-dev', 'x.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.x.x', false, false); testIsValidExtensionVersion('0.10.0-dev', '0.10.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.x.x', false, false); testIsValidExtensionVersion('1.10.0-dev', '1.10.x', false, false); // normal extensions with code testIsValidVersion('0.10.0-dev', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.0-dev', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.0-dev', '0.10.0', true); testIsValidVersion('0.10.0-dev', '0.10.2', false); testIsValidVersion('0.10.0-dev', '^0.10.2', false); testIsValidVersion('0.10.0-dev', '0.10.x', true); testIsValidVersion('0.10.0-dev', '^0.10.0', true); testIsValidVersion('0.10.0-dev', '*', false); // fails due to lack of specificity testIsValidVersion('0.10.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.0', '0.10.0', true); testIsValidVersion('0.10.0', '0.10.2', false); testIsValidVersion('0.10.0', '^0.10.2', false); testIsValidVersion('0.10.0', '0.10.x', true); testIsValidVersion('0.10.0', '^0.10.0', true); testIsValidVersion('0.10.0', '*', false); // fails due to lack of specificity testIsValidVersion('0.10.1', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.1', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.1', '0.10.0', false); testIsValidVersion('0.10.1', '0.10.2', false); testIsValidVersion('0.10.1', '^0.10.2', false); testIsValidVersion('0.10.1', '0.10.x', true); testIsValidVersion('0.10.1', '^0.10.0', true); testIsValidVersion('0.10.1', '*', false); // fails due to lack of specificity testIsValidVersion('0.10.100', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.100', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('0.10.100', '0.10.0', false); testIsValidVersion('0.10.100', '0.10.2', false); testIsValidVersion('0.10.100', '^0.10.2', true); testIsValidVersion('0.10.100', '0.10.x', true); testIsValidVersion('0.10.100', '^0.10.0', true); testIsValidVersion('0.10.100', '*', false); // fails due to lack of specificity testIsValidVersion('0.11.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('0.11.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('0.11.0', '0.10.0', false); testIsValidVersion('0.11.0', '0.10.2', false); testIsValidVersion('0.11.0', '^0.10.2', false); testIsValidVersion('0.11.0', '0.10.x', false); testIsValidVersion('0.11.0', '^0.10.0', false); testIsValidVersion('0.11.0', '*', false); // fails due to lack of specificity testIsValidVersion('1.0.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.0', '0.10.0', false); testIsValidVersion('1.0.0', '0.10.2', false); testIsValidVersion('1.0.0', '^0.10.2', true); testIsValidVersion('1.0.0', '0.10.x', true); testIsValidVersion('1.0.0', '^0.10.0', true); testIsValidVersion('1.0.0', '*', false); // fails due to lack of specificity testIsValidVersion('1.10.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('1.10.0', '1.x.x', true); testIsValidVersion('1.10.0', '1.10.0', true); testIsValidVersion('1.10.0', '1.10.2', false); testIsValidVersion('1.10.0', '^1.10.2', false); testIsValidVersion('1.10.0', '1.10.x', true); testIsValidVersion('1.10.0', '^1.10.0', true); testIsValidVersion('1.10.0', '*', false); // fails due to lack of specificity // Anything < 1.0.0 is compatible testIsValidVersion('1.0.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.0', '0.10.0', false); testIsValidVersion('1.0.0', '0.10.2', false); testIsValidVersion('1.0.0', '^0.10.2', true); testIsValidVersion('1.0.0', '0.10.x', true); testIsValidVersion('1.0.0', '^0.10.0', true); testIsValidVersion('1.0.0', '1.0.0', true); testIsValidVersion('1.0.0', '^1.0.0', true); testIsValidVersion('1.0.0', '^2.0.0', false); testIsValidVersion('1.0.0', '*', false); // fails due to lack of specificity testIsValidVersion('1.0.100', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.100', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('1.0.100', '0.10.0', false); testIsValidVersion('1.0.100', '0.10.2', false); testIsValidVersion('1.0.100', '^0.10.2', true); testIsValidVersion('1.0.100', '0.10.x', true); testIsValidVersion('1.0.100', '^0.10.0', true); testIsValidVersion('1.0.100', '1.0.0', false); testIsValidVersion('1.0.100', '^1.0.0', true); testIsValidVersion('1.0.100', '^1.0.1', true); testIsValidVersion('1.0.100', '^2.0.0', false); testIsValidVersion('1.0.100', '*', false); // fails due to lack of specificity testIsValidVersion('1.100.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('1.100.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('1.100.0', '0.10.0', false); testIsValidVersion('1.100.0', '0.10.2', false); testIsValidVersion('1.100.0', '^0.10.2', true); testIsValidVersion('1.100.0', '0.10.x', true); testIsValidVersion('1.100.0', '^0.10.0', true); testIsValidVersion('1.100.0', '1.0.0', false); testIsValidVersion('1.100.0', '^1.0.0', true); testIsValidVersion('1.100.0', '^1.1.0', true); testIsValidVersion('1.100.0', '^1.100.0', true); testIsValidVersion('1.100.0', '^2.0.0', false); testIsValidVersion('1.100.0', '*', false); // fails due to lack of specificity testIsValidVersion('2.0.0', 'x.x.x', false); // fails due to lack of specificity testIsValidVersion('2.0.0', '0.x.x', false); // fails due to lack of specificity testIsValidVersion('2.0.0', '0.10.0', false); testIsValidVersion('2.0.0', '0.10.2', false); testIsValidVersion('2.0.0', '^0.10.2', false); testIsValidVersion('2.0.0', '0.10.x', false); testIsValidVersion('2.0.0', '^0.10.0', false); testIsValidVersion('2.0.0', '1.0.0', false); testIsValidVersion('2.0.0', '^1.0.0', false); testIsValidVersion('2.0.0', '^1.1.0', false); testIsValidVersion('2.0.0', '^1.100.0', false); testIsValidVersion('2.0.0', '^2.0.0', true); testIsValidVersion('2.0.0', '*', false); // fails due to lack of specificity }); });
the_stack