text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import cn from 'classnames' import PropTypes from 'prop-types' import React, { useRef } from 'react' import { useUncontrolled } from 'uncontrollable' import Button from './Button' import { caretDown, caretUp } from './Icon' import { useLocalizer, Localizer } from './Localization' import NumberInput from './NumberInput' import Widget, { WidgetProps } from './Widget' import WidgetPicker from './WidgetPicker' import * as CustomPropTypes from './PropTypes' import useFocusManager from './useFocusManager' import { notify } from './WidgetHelpers' import { WidgetHTMLProps } from './shared' import useEventCallback from '@restart/hooks/useEventCallback' // my tests in ie11/chrome/FF indicate that keyDown repeats // at about 35ms+/- 5ms after an initial 500ms delay. callback fires on the leading edge function createInterval(callback: () => void) { let fn: () => void let id: number const cancel = () => clearTimeout(id) id = window.setTimeout( (fn = () => { id = window.setTimeout(fn, 35) callback() //fire after everything in case the user cancels on the first call }), 500, ) return cancel } function clamp(value: number | null | undefined, min: number, max: number) { max = max == null ? Infinity : max min = min == null ? -Infinity : min if (value == null || (value as any) === '') return null return Math.max( Math.min(typeof value == 'string' ? parseInt(value) : value, max), min, ) } const propTypes = { /** * @example ['valuePicker', [ [1, null] ]] */ value: PropTypes.number, /** * @example ['onChangePicker', [ [1, null] ]] */ onChange: PropTypes.func, /** * The minimum number that the NumberPicker value. * @example ['prop', ['min', 0]] */ min: PropTypes.number, /** * The maximum number that the NumberPicker value. * * @example ['prop', ['max', 0]] */ max: PropTypes.number, /** * Amount to increase or decrease value when using the spinner buttons. * * @example ['prop', ['step', 5]] */ step: PropTypes.number, /** * Specify how precise the `value` should be when typing, incrementing, or decrementing the value. * When empty, precision is parsed from the current `format` and culture. */ precision: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['auto'])]), /** * A format string used to display the number value. Localizer dependent, read about [localization](localization) for more info. * * @example ['prop', { max: 1, min: -1 , defaultValue: 0.2585, format: "{ style: 'percent' }" }] */ format: PropTypes.any, parse: PropTypes.func, incrementIcon: PropTypes.node, decrementIcon: PropTypes.node, /** @ignore */ tabIndex: PropTypes.any, name: PropTypes.string, placeholder: PropTypes.string, onKeyDown: PropTypes.func, onKeyPress: PropTypes.func, onKeyUp: PropTypes.func, autoFocus: PropTypes.bool, /** * @example ['disabled', ['1']] */ disabled: CustomPropTypes.disabled, /** * @example ['readOnly', ['1.5']] */ readOnly: CustomPropTypes.disabled, /** Adds a css class to the input container element. */ containerClassName: PropTypes.string, inputProps: PropTypes.object, messages: PropTypes.shape({ increment: PropTypes.string, decrement: PropTypes.string, }), /** @ignore */ localizer: PropTypes.object, } const defaultProps = { incrementIcon: caretUp, decrementIcon: caretDown, min: -Infinity, max: Infinity, step: 1, precision: 'auto', } export interface NumberPickerProps extends WidgetHTMLProps, Omit<WidgetProps, 'onChange'> { /** * @example ['valuePicker', [ [1, null] ]] */ value?: number | undefined /** * @example ['onChangePicker', [ [1, null] ]] */ onChange?: ( nextValue: number | null, ctx: { rawValue: number originalEvent: React.SyntheticEvent< HTMLDivElement | HTMLButtonElement > | null lastValue: number | undefined }, ) => void /** * The minimum number that the NumberPicker value. * @example ['prop', ['min', 0]] */ min?: number /** * The maximum number that the NumberPicker value. * * @example ['prop', ['max', 0]] */ max?: number /** * Amount to increase or decrease value when using the spinner buttons. * * @example ['prop', ['step', 5]] */ step?: number /** * Specify the decimal precision of the value when incrementing or decrementing by the * `step` value. This may be necessary to work around rounding issues due to * floating point math. By default the precision value used will be inferred * from the `step` and `value`, rounding the result to that. */ precision?: number | 'auto' /** * A format string used to display the number value. Localizer dependent, read [localization](./localization) for more info. * * @example ['prop', { max: 1, min: -1 , defaultValue: 0.2585, format: "{ style: 'percent' }" }] */ format?: string /** * Determines how the NumberPicker parses a number from the localized string representation. * * ```jsx live * import NumberPicker from 'react-widgets/NumberPicker'; * * <NumberPicker * parse={(strValue, localizer) => { * return localizer.parseNumber(strValue.replace('_', '')) * }} * /> * ``` * * @example false */ parse?: (str: string, localizer: Localizer) => number incrementIcon?: React.ReactNode decrementIcon?: React.ReactNode /** @ignore */ tabIndex?: number name?: string placeholder?: string onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void onKeyPress?: (event: React.KeyboardEvent<HTMLDivElement>) => void onKeyUp?: (event: React.KeyboardEvent<HTMLDivElement>) => void autoFocus?: boolean /** * @example ['disabled', ['1']] */ disabled?: boolean /** * @example ['readOnly', ['1.5']] */ readOnly?: boolean /** Adds a css class to the input container element. */ containerClassName?: string inputProps?: React.HtmlHTMLAttributes<HTMLInputElement> messages?: { increment?: string decrement?: string } /** @ignore */ localizer?: Localizer } /** * --- * localized: true * shortcuts: * - { key: down arrow, label: decrement value } * - { key: up arrow, label: increment value } * - { key: home, label: set value to minimum value, if finite } * - { key: end, label: set value to maximum value, if finite } * --- * * @public */ function NumberPicker(uncontrolledProps: NumberPickerProps) { const { className, containerClassName, disabled, readOnly, value, min, max, incrementIcon, decrementIcon, placeholder, autoFocus, tabIndex, parse, name, onChange, messages, format, onKeyDown, onKeyPress, onKeyUp, inputProps, precision, step: pStep, ...elementProps } = useUncontrolled(uncontrolledProps, { value: 'onChange' }) const localizer = useLocalizer(messages, { number: format }) const ref = useRef<HTMLDivElement>(null) const inputRef = useRef<HTMLInputElement>(null) const repeaterRef = useRef<(() => void) | null>(null) const [focusEvents, focused] = useFocusManager(ref, uncontrolledProps, { willHandle(focused) { if (focused) focus() }, }) const handleMouseDown = useEventCallback( ( direction: 'UP' | 'DOWN', event: | React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLInputElement>, ) => { if (event) event.persist() let method = direction === 'UP' ? increment : decrement let value = method(event), atTop = direction === 'UP' && value === max, atBottom = direction === 'DOWN' && value === min if (atTop || atBottom) handleMouseUp() else if (!repeaterRef.current) { repeaterRef.current = createInterval(() => { handleMouseDown(direction, event) }) } }, ) const handleMouseUp = useEventCallback(() => { if (!repeaterRef.current) return repeaterRef.current() repeaterRef.current = null }) const handleKeyDown = useEventCallback( (event: React.KeyboardEvent<HTMLDivElement>) => { if (readOnly) return let key = event.key notify(onKeyDown, [event]) if (event.defaultPrevented) return if (key === 'End' && isFinite(max!)) handleChange(max!, event) else if (key === 'Home' && isFinite(min!)) handleChange(min!, event) else if (key === 'ArrowDown') { event.preventDefault() decrement(event) } else if (key === 'ArrowUp') { event.preventDefault() increment(event) } }, ) const handleChange = ( rawValue: number, originalEvent: React.SyntheticEvent< HTMLDivElement | HTMLButtonElement > | null = null, ) => { let nextValue = clamp(rawValue, min!, max!) if (value !== nextValue) notify(onChange, [ nextValue, { rawValue, originalEvent, lastValue: value, }, ]) } function focus() { inputRef.current?.focus() } function increment( event: | React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLButtonElement>, ) { return step(pStep!, event) } function decrement( event: | React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLButtonElement>, ) { return step(-pStep!, event) } function step( amount: number, event: | React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLButtonElement>, ) { const nextValue = (value || 0) + amount let p: number | undefined = precision === 'auto' ? Math.max(getPrecision(value || 0), getPrecision(amount)) : precision handleChange( p != null ? parseFloat(nextValue.toFixed(p)) : nextValue, event, ) return nextValue } const clampedValue = clamp(value, min!, max!) return ( <Widget {...elementProps} focused={focused} disabled={disabled} readOnly={readOnly} onKeyDown={handleKeyDown} {...focusEvents} ref={ref} className={cn(className, 'rw-number-picker')} > <WidgetPicker className={containerClassName}> <NumberInput {...inputProps} role="spinbutton" tabIndex={tabIndex} value={clampedValue} placeholder={placeholder} autoFocus={autoFocus} editing={focused} localizer={localizer} parse={parse} name={name} min={min} max={max} disabled={disabled} readOnly={readOnly} onChange={handleChange} onKeyPress={onKeyPress} onKeyUp={onKeyUp} innerRef={inputRef} /> <span className="rw-input-addon rw-number-picker-spinners"> <Button icon={incrementIcon} className="rw-picker-btn" disabled={clampedValue === max || disabled || readOnly} label={(localizer.messages.increment as any)({ value: clampedValue, min, max, })} onMouseUp={() => handleMouseUp()} onMouseDown={(e) => handleMouseDown('UP', e)} onMouseLeave={() => handleMouseUp()} /> <Button icon={decrementIcon} className="rw-picker-btn" disabled={clampedValue === min || disabled || readOnly} label={(localizer.messages.decrement as any)({ value: clampedValue, min, max, })} onMouseUp={() => handleMouseUp()} onMouseDown={(e) => handleMouseDown('DOWN', e)} onMouseLeave={() => handleMouseUp()} /> </span> </WidgetPicker> </Widget> ) } ;(NumberPicker as any).propTypes = propTypes ;(NumberPicker as any).defaultProps = defaultProps export default NumberPicker function getPrecision(a: number) { if (!isFinite(a)) return 0 let e = 1 let p = 0 while (Math.round(a * e) / e !== a) { e *= 10 p++ } return p }
the_stack
type RawFrame = { type: string; size: number; data: Uint8Array }; // breaking up those two types in order to clarify what is happening in the decoding path. type DecodedFrame<T> = { key: string; data: T; info?: any }; export type Frame = DecodedFrame<ArrayBuffer | string>; /** * Returns true if an ID3 header can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 header is found */ export const isHeader = (data: Uint8Array, offset: number): boolean => { /* * http://id3.org/id3v2.3.0 * [0] = 'I' * [1] = 'D' * [2] = '3' * [3,4] = {Version} * [5] = {Flags} * [6-9] = {ID3 Size} * * An ID3v2 tag can be detected with the following pattern: * $49 44 33 yy yy xx zz zz zz zz * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80 */ if (offset + 10 <= data.length) { // look for 'ID3' identifier if ( data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33 ) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if ( data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80 ) { return true; } } } } return false; }; /** * Returns true if an ID3 footer can be found at offset in data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {boolean} - True if an ID3 footer is found */ export const isFooter = (data: Uint8Array, offset: number): boolean => { /* * The footer is a copy of the header, but with a different identifier */ if (offset + 10 <= data.length) { // look for '3DI' identifier if ( data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49 ) { // check version is within range if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) { // check size is within range if ( data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80 ) { return true; } } } } return false; }; /** * Returns any adjacent ID3 tags found in data starting at offset, as one block of data * @param {Uint8Array} data - The data to search in * @param {number} offset - The offset at which to start searching * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found * or *undefined* if no header is found at the starting offset */ export const getID3Data = ( data: Uint8Array, offset: number ): Uint8Array | undefined => { const front = offset; let length = 0; while (isHeader(data, offset)) { // ID3 header is 10 bytes length += 10; const size = readSize(data, offset + 6); length += size; if (isFooter(data, offset + 10)) { // ID3 footer is 10 bytes length += 10; } offset += length; } if (length > 0) { return data.subarray(front, front + length); } return undefined; }; const readSize = (data: Uint8Array, offset: number): number => { let size = 0; size = (data[offset] & 0x7f) << 21; size |= (data[offset + 1] & 0x7f) << 14; size |= (data[offset + 2] & 0x7f) << 7; size |= data[offset + 3] & 0x7f; return size; }; export const canParse = (data: Uint8Array, offset: number): boolean => { return ( isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset ); }; /** * Searches for the Elementary Stream timestamp found in the ID3 data chunk * @param {Uint8Array} data - Block of data containing one or more ID3 tags * @return {number | undefined} - The timestamp */ export const getTimeStamp = (data: Uint8Array): number | undefined => { const frames: Frame[] = getID3Frames(data); for (let i = 0; i < frames.length; i++) { const frame = frames[i]; if (isTimeStampFrame(frame)) { return readTimeStamp(frame as DecodedFrame<ArrayBuffer>); } } return undefined; }; /** * Returns true if the ID3 frame is an Elementary Stream timestamp frame * @param {ID3 frame} frame */ export const isTimeStampFrame = (frame: Frame): boolean => { return ( frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp' ); }; const getFrameData = (data: Uint8Array): RawFrame => { /* Frame ID $xx xx xx xx (four characters) Size $xx xx xx xx Flags $xx xx */ const type: string = String.fromCharCode(data[0], data[1], data[2], data[3]); const size: number = readSize(data, 4); // skip frame id, size, and flags const offset = 10; return { type, size, data: data.subarray(offset, offset + size) }; }; /** * Returns an array of ID3 frames found in all the ID3 tags in the id3Data * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags * @return {ID3.Frame[]} - Array of ID3 frame objects */ export const getID3Frames = (id3Data: Uint8Array): Frame[] => { let offset = 0; const frames: Frame[] = []; while (isHeader(id3Data, offset)) { const size = readSize(id3Data, offset + 6); // skip past ID3 header offset += 10; const end = offset + size; // loop through frames in the ID3 tag while (offset + 8 < end) { const frameData: RawFrame = getFrameData(id3Data.subarray(offset)); const frame: Frame | undefined = decodeFrame(frameData); if (frame) { frames.push(frame); } // skip frame header and frame data offset += frameData.size + 10; } if (isFooter(id3Data, offset)) { offset += 10; } } return frames; }; export const decodeFrame = (frame: RawFrame): Frame | undefined => { if (frame.type === 'PRIV') { return decodePrivFrame(frame); } else if (frame.type[0] === 'W') { return decodeURLFrame(frame); } return decodeTextFrame(frame); }; const decodePrivFrame = ( frame: RawFrame ): DecodedFrame<ArrayBuffer> | undefined => { /* Format: <text string>\0<binary data> */ if (frame.size < 2) { return undefined; } const owner = utf8ArrayToStr(frame.data, true); const privateData = new Uint8Array(frame.data.subarray(owner.length + 1)); return { key: frame.type, info: owner, data: privateData.buffer }; }; const decodeTextFrame = (frame: RawFrame): DecodedFrame<string> | undefined => { if (frame.size < 2) { return undefined; } if (frame.type === 'TXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{Value} */ let index = 1; const description = utf8ArrayToStr(frame.data.subarray(index), true); index += description.length + 1; const value = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0] = {Text Encoding} [1-?] = {Value} */ const text = utf8ArrayToStr(frame.data.subarray(1)); return { key: frame.type, data: text }; }; const decodeURLFrame = (frame: RawFrame): DecodedFrame<string> | undefined => { if (frame.type === 'WXXX') { /* Format: [0] = {Text Encoding} [1-?] = {Description}\0{URL} */ if (frame.size < 2) { return undefined; } let index = 1; const description: string = utf8ArrayToStr( frame.data.subarray(index), true ); index += description.length + 1; const value: string = utf8ArrayToStr(frame.data.subarray(index)); return { key: frame.type, info: description, data: value }; } /* Format: [0-?] = {URL} */ const url: string = utf8ArrayToStr(frame.data); return { key: frame.type, data: url }; }; const readTimeStamp = ( timeStampFrame: DecodedFrame<ArrayBuffer> ): number | undefined => { if (timeStampFrame.data.byteLength === 8) { const data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number, // with the upper 31 bits set to zero. const pts33Bit = data[3] & 0x1; let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7]; timestamp /= 45; if (pts33Bit) { timestamp += 47721858.84; } // 2^32 / 90 return Math.round(timestamp); } return undefined; }; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197 // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ export const utf8ArrayToStr = ( array: Uint8Array, exitOnNull: boolean = false ): string => { const decoder = getTextDecoder(); if (decoder) { const decoded = decoder.decode(array); if (exitOnNull) { // grab up to the first null const idx = decoded.indexOf('\0'); return idx !== -1 ? decoded.substring(0, idx) : decoded; } // remove any null characters return decoded.replace(/\0/g, ''); } const len = array.length; let c; let char2; let char3; let out = ''; let i = 0; while (i < len) { c = array[i++]; if (c === 0x00 && exitOnNull) { return out; } else if (c === 0x00 || c === 0x03) { // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it continue; } switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode( ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0) ); break; default: } } return out; }; export const testables = { decodeTextFrame: decodeTextFrame, }; let decoder: TextDecoder; function getTextDecoder() { if (!decoder && typeof self.TextDecoder !== 'undefined') { decoder = new self.TextDecoder('utf-8'); } return decoder; }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Operations { /** * Lists all of the available REST API operations of the Microsoft.Storsimple * provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AvailableProviderOperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AvailableProviderOperationList>>; /** * Lists all of the available REST API operations of the Microsoft.Storsimple * provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AvailableProviderOperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AvailableProviderOperationList} [result] - The deserialized result object if an error did not occur. * See {@link AvailableProviderOperationList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AvailableProviderOperationList>; list(callback: ServiceCallback<models.AvailableProviderOperationList>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AvailableProviderOperationList>): void; /** * Lists all of the available REST API operations of the Microsoft.Storsimple * provider * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AvailableProviderOperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AvailableProviderOperationList>>; /** * Lists all of the available REST API operations of the Microsoft.Storsimple * provider * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AvailableProviderOperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AvailableProviderOperationList} [result] - The deserialized result object if an error did not occur. * See {@link AvailableProviderOperationList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AvailableProviderOperationList>; listNext(nextPageLink: string, callback: ServiceCallback<models.AvailableProviderOperationList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AvailableProviderOperationList>): void; } /** * @class * Managers * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Managers { /** * Retrieves all the managers in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagerList>>; /** * Retrieves all the managers in a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagerList} [result] - The deserialized result object if an error did not occur. * See {@link ManagerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagerList>; list(callback: ServiceCallback<models.ManagerList>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagerList>): void; /** * Retrieves all the managers in a resource group. * * @param {string} resourceGroupName The resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagerList>>; /** * Retrieves all the managers in a resource group. * * @param {string} resourceGroupName The resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagerList} [result] - The deserialized result object if an error did not occur. * See {@link ManagerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagerList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ManagerList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagerList>): void; /** * Returns the properties of the specified manager name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Manager>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Manager>>; /** * Returns the properties of the specified manager name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Manager} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Manager} [result] - The deserialized result object if an error did not occur. * See {@link Manager} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Manager>; get(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Manager>): void; get(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Manager>): void; /** * Creates or updates the manager. * * @param {object} parameters The manager. * * @param {object} [parameters.cisIntrinsicSettings] Represents the type of * StorSimple Manager. * * @param {string} parameters.cisIntrinsicSettings.type The type of StorSimple * Manager. Possible values include: 'GardaV1', 'HelsinkiV1' * * @param {string} [parameters.provisioningState] Specifies the state of the * resource as it is getting provisioned. Value of "Succeeded" means the * Manager was successfully created. * * @param {string} [parameters.etag] The etag of the manager. * * @param {string} parameters.location The geo location of the resource. * * @param {object} [parameters.tags] The tags attached to the resource. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Manager>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(parameters: models.Manager, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Manager>>; /** * Creates or updates the manager. * * @param {object} parameters The manager. * * @param {object} [parameters.cisIntrinsicSettings] Represents the type of * StorSimple Manager. * * @param {string} parameters.cisIntrinsicSettings.type The type of StorSimple * Manager. Possible values include: 'GardaV1', 'HelsinkiV1' * * @param {string} [parameters.provisioningState] Specifies the state of the * resource as it is getting provisioned. Value of "Succeeded" means the * Manager was successfully created. * * @param {string} [parameters.etag] The etag of the manager. * * @param {string} parameters.location The geo location of the resource. * * @param {object} [parameters.tags] The tags attached to the resource. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Manager} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Manager} [result] - The deserialized result object if an error did not occur. * See {@link Manager} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(parameters: models.Manager, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Manager>; createOrUpdate(parameters: models.Manager, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Manager>): void; createOrUpdate(parameters: models.Manager, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Manager>): void; /** * Deletes the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates the StorSimple Manager. * * @param {object} parameters The manager update parameters. * * @param {object} [parameters.tags] The tags attached to the Manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Manager>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(parameters: models.ManagerPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Manager>>; /** * Updates the StorSimple Manager. * * @param {object} parameters The manager update parameters. * * @param {object} [parameters.tags] The tags attached to the Manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Manager} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Manager} [result] - The deserialized result object if an error did not occur. * See {@link Manager} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(parameters: models.ManagerPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Manager>; update(parameters: models.ManagerPatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Manager>): void; update(parameters: models.ManagerPatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Manager>): void; /** * Returns the public encryption key of the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PublicKey>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDevicePublicEncryptionKeyWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PublicKey>>; /** * Returns the public encryption key of the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PublicKey} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PublicKey} [result] - The deserialized result object if an error did not occur. * See {@link PublicKey} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDevicePublicEncryptionKey(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PublicKey>; getDevicePublicEncryptionKey(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.PublicKey>): void; getDevicePublicEncryptionKey(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PublicKey>): void; /** * Returns the encryption settings of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EncryptionSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getEncryptionSettingsWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EncryptionSettings>>; /** * Returns the encryption settings of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EncryptionSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EncryptionSettings} [result] - The deserialized result object if an error did not occur. * See {@link EncryptionSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getEncryptionSettings(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EncryptionSettings>; getEncryptionSettings(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.EncryptionSettings>): void; getEncryptionSettings(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EncryptionSettings>): void; /** * Returns the extended information of the specified manager name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagerExtendedInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getExtendedInfoWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagerExtendedInfo>>; /** * Returns the extended information of the specified manager name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagerExtendedInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagerExtendedInfo} [result] - The deserialized result object if an error did not occur. * See {@link ManagerExtendedInfo} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getExtendedInfo(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagerExtendedInfo>; getExtendedInfo(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.ManagerExtendedInfo>): void; getExtendedInfo(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagerExtendedInfo>): void; /** * Creates the extended info of the manager. * * @param {object} parameters The manager extended information. * * @param {string} [parameters.version] The version of the extended info being * persisted. * * @param {string} parameters.integrityKey Represents the CIK of the resource. * * @param {string} [parameters.encryptionKey] Represents the CEK of the * resource. * * @param {string} [parameters.encryptionKeyThumbprint] Represents the Cert * thumbprint that was used to encrypt the CEK. * * @param {string} [parameters.portalCertificateThumbprint] Represents the * portal thumbprint which can be used optionally to encrypt the entire data * before storing it. * * @param {string} parameters.algorithm Represents the encryption algorithm * used to encrypt the keys. None - if Key is saved in plain text format. * Algorithm name - if key is encrypted * * @param {string} [parameters.etag] The etag of the resource. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagerExtendedInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createExtendedInfoWithHttpOperationResponse(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagerExtendedInfo>>; /** * Creates the extended info of the manager. * * @param {object} parameters The manager extended information. * * @param {string} [parameters.version] The version of the extended info being * persisted. * * @param {string} parameters.integrityKey Represents the CIK of the resource. * * @param {string} [parameters.encryptionKey] Represents the CEK of the * resource. * * @param {string} [parameters.encryptionKeyThumbprint] Represents the Cert * thumbprint that was used to encrypt the CEK. * * @param {string} [parameters.portalCertificateThumbprint] Represents the * portal thumbprint which can be used optionally to encrypt the entire data * before storing it. * * @param {string} parameters.algorithm Represents the encryption algorithm * used to encrypt the keys. None - if Key is saved in plain text format. * Algorithm name - if key is encrypted * * @param {string} [parameters.etag] The etag of the resource. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagerExtendedInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagerExtendedInfo} [result] - The deserialized result object if an error did not occur. * See {@link ManagerExtendedInfo} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagerExtendedInfo>; createExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.ManagerExtendedInfo>): void; createExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagerExtendedInfo>): void; /** * Deletes the extended info of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteExtendedInfoWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the extended info of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteExtendedInfo(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteExtendedInfo(resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteExtendedInfo(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates the extended info of the manager. * * @param {object} parameters The manager extended information. * * @param {string} [parameters.version] The version of the extended info being * persisted. * * @param {string} parameters.integrityKey Represents the CIK of the resource. * * @param {string} [parameters.encryptionKey] Represents the CEK of the * resource. * * @param {string} [parameters.encryptionKeyThumbprint] Represents the Cert * thumbprint that was used to encrypt the CEK. * * @param {string} [parameters.portalCertificateThumbprint] Represents the * portal thumbprint which can be used optionally to encrypt the entire data * before storing it. * * @param {string} parameters.algorithm Represents the encryption algorithm * used to encrypt the keys. None - if Key is saved in plain text format. * Algorithm name - if key is encrypted * * @param {string} [parameters.etag] The etag of the resource. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} ifMatch Pass the ETag of ExtendedInfo fetched from GET call * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagerExtendedInfo>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateExtendedInfoWithHttpOperationResponse(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagerExtendedInfo>>; /** * Updates the extended info of the manager. * * @param {object} parameters The manager extended information. * * @param {string} [parameters.version] The version of the extended info being * persisted. * * @param {string} parameters.integrityKey Represents the CIK of the resource. * * @param {string} [parameters.encryptionKey] Represents the CEK of the * resource. * * @param {string} [parameters.encryptionKeyThumbprint] Represents the Cert * thumbprint that was used to encrypt the CEK. * * @param {string} [parameters.portalCertificateThumbprint] Represents the * portal thumbprint which can be used optionally to encrypt the entire data * before storing it. * * @param {string} parameters.algorithm Represents the encryption algorithm * used to encrypt the keys. None - if Key is saved in plain text format. * Algorithm name - if key is encrypted * * @param {string} [parameters.etag] The etag of the resource. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} ifMatch Pass the ETag of ExtendedInfo fetched from GET call * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagerExtendedInfo} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagerExtendedInfo} [result] - The deserialized result object if an error did not occur. * See {@link ManagerExtendedInfo} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updateExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagerExtendedInfo>; updateExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, callback: ServiceCallback<models.ManagerExtendedInfo>): void; updateExtendedInfo(parameters: models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagerExtendedInfo>): void; /** * Lists the features and their support status * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FeatureList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listFeatureSupportStatusWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FeatureList>>; /** * Lists the features and their support status * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FeatureList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FeatureList} [result] - The deserialized result object if an error did not occur. * See {@link FeatureList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listFeatureSupportStatus(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.FeatureList>; listFeatureSupportStatus(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.FeatureList>): void; listFeatureSupportStatus(resourceGroupName: string, managerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FeatureList>): void; /** * Returns the activation key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Key>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getActivationKeyWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Key>>; /** * Returns the activation key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Key} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Key} [result] - The deserialized result object if an error did not occur. * See {@link Key} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getActivationKey(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Key>; getActivationKey(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Key>): void; getActivationKey(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Key>): void; /** * Returns the symmetric encrypted public encryption key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SymmetricEncryptedSecret>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getPublicEncryptionKeyWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SymmetricEncryptedSecret>>; /** * Returns the symmetric encrypted public encryption key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SymmetricEncryptedSecret} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SymmetricEncryptedSecret} [result] - The deserialized result object if an error did not occur. * See {@link SymmetricEncryptedSecret} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getPublicEncryptionKey(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SymmetricEncryptedSecret>; getPublicEncryptionKey(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.SymmetricEncryptedSecret>): void; getPublicEncryptionKey(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SymmetricEncryptedSecret>): void; /** * Gets the metrics for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricsWithHttpOperationResponse(resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricList>>; /** * Gets the metrics for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricList} [result] - The deserialized result object if an error did not occur. * See {@link MetricList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetrics(resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricList>; listMetrics(resourceGroupName: string, managerName: string, filter: string, callback: ServiceCallback<models.MetricList>): void; listMetrics(resourceGroupName: string, managerName: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricList>): void; /** * Gets the metric definitions for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricDefinitionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricDefinitionWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricDefinitionList>>; /** * Gets the metric definitions for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricDefinitionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricDefinitionList} [result] - The deserialized result object if an error did not occur. * See {@link MetricDefinitionList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetricDefinition(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricDefinitionList>; listMetricDefinition(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.MetricDefinitionList>): void; listMetricDefinition(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricDefinitionList>): void; /** * Re-generates and returns the activation key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Key>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateActivationKeyWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Key>>; /** * Re-generates and returns the activation key of the manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Key} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Key} [result] - The deserialized result object if an error did not occur. * See {@link Key} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateActivationKey(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Key>; regenerateActivationKey(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Key>): void; regenerateActivationKey(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Key>): void; } /** * @class * AccessControlRecords * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface AccessControlRecords { /** * Retrieves all the access control records in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessControlRecordList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessControlRecordList>>; /** * Retrieves all the access control records in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessControlRecordList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessControlRecordList} [result] - The deserialized result object if an error did not occur. * See {@link AccessControlRecordList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessControlRecordList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AccessControlRecordList>): void; listByManager(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessControlRecordList>): void; /** * Returns the properties of the specified access control record name. * * @param {string} accessControlRecordName Name of access control record to be * fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessControlRecord>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessControlRecord>>; /** * Returns the properties of the specified access control record name. * * @param {string} accessControlRecordName Name of access control record to be * fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessControlRecord} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessControlRecord} [result] - The deserialized result object if an error did not occur. * See {@link AccessControlRecord} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessControlRecord>; get(accessControlRecordName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AccessControlRecord>): void; get(accessControlRecordName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessControlRecord>): void; /** * Creates or Updates an access control record. * * @param {string} accessControlRecordName The name of the access control * record. * * @param {object} parameters The access control record to be added or updated. * * @param {string} parameters.initiatorName The iSCSI initiator name (IQN). * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessControlRecord>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessControlRecord>>; /** * Creates or Updates an access control record. * * @param {string} accessControlRecordName The name of the access control * record. * * @param {object} parameters The access control record to be added or updated. * * @param {string} parameters.initiatorName The iSCSI initiator name (IQN). * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessControlRecord} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessControlRecord} [result] - The deserialized result object if an error did not occur. * See {@link AccessControlRecord} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessControlRecord>; createOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AccessControlRecord>): void; createOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessControlRecord>): void; /** * Deletes the access control record. * * @param {string} accessControlRecordName The name of the access control * record to delete. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the access control record. * * @param {string} accessControlRecordName The name of the access control * record to delete. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or Updates an access control record. * * @param {string} accessControlRecordName The name of the access control * record. * * @param {object} parameters The access control record to be added or updated. * * @param {string} parameters.initiatorName The iSCSI initiator name (IQN). * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccessControlRecord>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessControlRecord>>; /** * Creates or Updates an access control record. * * @param {string} accessControlRecordName The name of the access control * record. * * @param {object} parameters The access control record to be added or updated. * * @param {string} parameters.initiatorName The iSCSI initiator name (IQN). * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AccessControlRecord} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AccessControlRecord} [result] - The deserialized result object if an error did not occur. * See {@link AccessControlRecord} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessControlRecord>; beginCreateOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AccessControlRecord>): void; beginCreateOrUpdate(accessControlRecordName: string, parameters: models.AccessControlRecord, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessControlRecord>): void; /** * Deletes the access control record. * * @param {string} accessControlRecordName The name of the access control * record to delete. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the access control record. * * @param {string} accessControlRecordName The name of the access control * record to delete. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(accessControlRecordName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Alerts * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Alerts { /** * Retrieves all the alerts in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>; /** * Retrieves all the alerts in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertList} [result] - The deserialized result object if an error did not occur. * See {@link AlertList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AlertList>): void; listByManager(resourceGroupName: string, managerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void; /** * Clear the alerts. * * @param {object} parameters The clear alert request. * * @param {string} [parameters.resolutionMessage] The resolution message while * clearing the alert * * @param {array} parameters.alerts The list of alert IDs to be cleared * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ clearWithHttpOperationResponse(parameters: models.ClearAlertRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Clear the alerts. * * @param {object} parameters The clear alert request. * * @param {string} [parameters.resolutionMessage] The resolution message while * clearing the alert * * @param {array} parameters.alerts The list of alert IDs to be cleared * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ clear(parameters: models.ClearAlertRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; clear(parameters: models.ClearAlertRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; clear(parameters: models.ClearAlertRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Sends a test alert email. * * @param {string} deviceName The device name * * @param {object} parameters The send test alert email request. * * @param {array} parameters.emailList The list of email IDs to send the test * alert email * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ sendTestEmailWithHttpOperationResponse(deviceName: string, parameters: models.SendTestAlertEmailRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Sends a test alert email. * * @param {string} deviceName The device name * * @param {object} parameters The send test alert email request. * * @param {array} parameters.emailList The list of email IDs to send the test * alert email * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ sendTestEmail(deviceName: string, parameters: models.SendTestAlertEmailRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; sendTestEmail(deviceName: string, parameters: models.SendTestAlertEmailRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; sendTestEmail(deviceName: string, parameters: models.SendTestAlertEmailRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Retrieves all the alerts in a manager. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertList>>; /** * Retrieves all the alerts in a manager. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertList} [result] - The deserialized result object if an error did not occur. * See {@link AlertList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagerNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertList>; listByManagerNext(nextPageLink: string, callback: ServiceCallback<models.AlertList>): void; listByManagerNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertList>): void; } /** * @class * BandwidthSettings * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface BandwidthSettings { /** * Retrieves all the bandwidth setting in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BandwidthSettingList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BandwidthSettingList>>; /** * Retrieves all the bandwidth setting in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BandwidthSettingList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BandwidthSettingList} [result] - The deserialized result object if an error did not occur. * See {@link BandwidthSettingList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BandwidthSettingList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BandwidthSettingList>): void; listByManager(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BandwidthSettingList>): void; /** * Returns the properties of the specified bandwidth setting name. * * @param {string} bandwidthSettingName The name of bandwidth setting to be * fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BandwidthSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BandwidthSetting>>; /** * Returns the properties of the specified bandwidth setting name. * * @param {string} bandwidthSettingName The name of bandwidth setting to be * fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BandwidthSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BandwidthSetting} [result] - The deserialized result object if an error did not occur. * See {@link BandwidthSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BandwidthSetting>; get(bandwidthSettingName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BandwidthSetting>): void; get(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BandwidthSetting>): void; /** * Creates or updates the bandwidth setting * * @param {string} bandwidthSettingName The bandwidth setting name. * * @param {object} parameters The bandwidth setting to be added or updated. * * @param {array} parameters.schedules The schedules. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BandwidthSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BandwidthSetting>>; /** * Creates or updates the bandwidth setting * * @param {string} bandwidthSettingName The bandwidth setting name. * * @param {object} parameters The bandwidth setting to be added or updated. * * @param {array} parameters.schedules The schedules. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BandwidthSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BandwidthSetting} [result] - The deserialized result object if an error did not occur. * See {@link BandwidthSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BandwidthSetting>; createOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BandwidthSetting>): void; createOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BandwidthSetting>): void; /** * Deletes the bandwidth setting * * @param {string} bandwidthSettingName The name of the bandwidth setting. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the bandwidth setting * * @param {string} bandwidthSettingName The name of the bandwidth setting. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or updates the bandwidth setting * * @param {string} bandwidthSettingName The bandwidth setting name. * * @param {object} parameters The bandwidth setting to be added or updated. * * @param {array} parameters.schedules The schedules. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BandwidthSetting>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BandwidthSetting>>; /** * Creates or updates the bandwidth setting * * @param {string} bandwidthSettingName The bandwidth setting name. * * @param {object} parameters The bandwidth setting to be added or updated. * * @param {array} parameters.schedules The schedules. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BandwidthSetting} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BandwidthSetting} [result] - The deserialized result object if an error did not occur. * See {@link BandwidthSetting} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BandwidthSetting>; beginCreateOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BandwidthSetting>): void; beginCreateOrUpdate(bandwidthSettingName: string, parameters: models.BandwidthSetting, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BandwidthSetting>): void; /** * Deletes the bandwidth setting * * @param {string} bandwidthSettingName The name of the bandwidth setting. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the bandwidth setting * * @param {string} bandwidthSettingName The name of the bandwidth setting. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(bandwidthSettingName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * CloudAppliances * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface CloudAppliances { /** * Lists supported cloud appliance models and supported configurations. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CloudApplianceConfigurationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSupportedConfigurationsWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CloudApplianceConfigurationList>>; /** * Lists supported cloud appliance models and supported configurations. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CloudApplianceConfigurationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CloudApplianceConfigurationList} [result] - The deserialized result object if an error did not occur. * See {@link CloudApplianceConfigurationList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSupportedConfigurations(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CloudApplianceConfigurationList>; listSupportedConfigurations(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.CloudApplianceConfigurationList>): void; listSupportedConfigurations(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CloudApplianceConfigurationList>): void; /** * Provisions cloud appliance. * * @param {object} parameters The cloud appliance * * @param {string} parameters.name The name. * * @param {string} [parameters.vnetName] The name of the virtual network. * * @param {string} parameters.vnetRegion The virtual network region. * * @param {boolean} [parameters.isVnetDnsConfigured] Indicates whether virtual * network used is configured with DNS or not. * * @param {boolean} [parameters.isVnetExpressConfigured] Indicates whether * virtual network used is configured with express route or not. * * @param {string} [parameters.subnetName] The name of the subnet. * * @param {string} [parameters.storageAccountName] The name of the storage * account. * * @param {string} [parameters.storageAccountType] The type of the storage * account. * * @param {string} [parameters.vmType] The type of the virtual machine. * * @param {string} [parameters.vmImageName] The name of the virtual machine * image. * * @param {string} [parameters.modelNumber] The model number. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ provisionWithHttpOperationResponse(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Provisions cloud appliance. * * @param {object} parameters The cloud appliance * * @param {string} parameters.name The name. * * @param {string} [parameters.vnetName] The name of the virtual network. * * @param {string} parameters.vnetRegion The virtual network region. * * @param {boolean} [parameters.isVnetDnsConfigured] Indicates whether virtual * network used is configured with DNS or not. * * @param {boolean} [parameters.isVnetExpressConfigured] Indicates whether * virtual network used is configured with express route or not. * * @param {string} [parameters.subnetName] The name of the subnet. * * @param {string} [parameters.storageAccountName] The name of the storage * account. * * @param {string} [parameters.storageAccountType] The type of the storage * account. * * @param {string} [parameters.vmType] The type of the virtual machine. * * @param {string} [parameters.vmImageName] The name of the virtual machine * image. * * @param {string} [parameters.modelNumber] The model number. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ provision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; provision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; provision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Provisions cloud appliance. * * @param {object} parameters The cloud appliance * * @param {string} parameters.name The name. * * @param {string} [parameters.vnetName] The name of the virtual network. * * @param {string} parameters.vnetRegion The virtual network region. * * @param {boolean} [parameters.isVnetDnsConfigured] Indicates whether virtual * network used is configured with DNS or not. * * @param {boolean} [parameters.isVnetExpressConfigured] Indicates whether * virtual network used is configured with express route or not. * * @param {string} [parameters.subnetName] The name of the subnet. * * @param {string} [parameters.storageAccountName] The name of the storage * account. * * @param {string} [parameters.storageAccountType] The type of the storage * account. * * @param {string} [parameters.vmType] The type of the virtual machine. * * @param {string} [parameters.vmImageName] The name of the virtual machine * image. * * @param {string} [parameters.modelNumber] The model number. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginProvisionWithHttpOperationResponse(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Provisions cloud appliance. * * @param {object} parameters The cloud appliance * * @param {string} parameters.name The name. * * @param {string} [parameters.vnetName] The name of the virtual network. * * @param {string} parameters.vnetRegion The virtual network region. * * @param {boolean} [parameters.isVnetDnsConfigured] Indicates whether virtual * network used is configured with DNS or not. * * @param {boolean} [parameters.isVnetExpressConfigured] Indicates whether * virtual network used is configured with express route or not. * * @param {string} [parameters.subnetName] The name of the subnet. * * @param {string} [parameters.storageAccountName] The name of the storage * account. * * @param {string} [parameters.storageAccountType] The type of the storage * account. * * @param {string} [parameters.vmType] The type of the virtual machine. * * @param {string} [parameters.vmImageName] The name of the virtual machine * image. * * @param {string} [parameters.modelNumber] The model number. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginProvision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginProvision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginProvision(parameters: models.CloudAppliance, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Devices * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Devices { /** * Complete minimal setup before using the device. * * @param {object} parameters The minimal properties to configure a device. * * @param {string} parameters.friendlyName The friendly name for the device. * * @param {string} parameters.currentDeviceName The current name of the device. * * @param {string} parameters.timeZone The device time zone. For eg: "Pacific * Standard Time" * * @param {object} [parameters.dnsSettings] The secondary DNS Settings of the * device. * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The list of * secondary DNS Server IP addresses. * * @param {object} [parameters.networkInterfaceData0Settings] The 'Data 0' * network interface card settings. * * @param {string} [parameters.networkInterfaceData0Settings.controllerZeroIp] * The controller 0's IPv4 address. * * @param {string} [parameters.networkInterfaceData0Settings.controllerOneIp] * The controller 1's IPv4 address. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ configureWithHttpOperationResponse(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Complete minimal setup before using the device. * * @param {object} parameters The minimal properties to configure a device. * * @param {string} parameters.friendlyName The friendly name for the device. * * @param {string} parameters.currentDeviceName The current name of the device. * * @param {string} parameters.timeZone The device time zone. For eg: "Pacific * Standard Time" * * @param {object} [parameters.dnsSettings] The secondary DNS Settings of the * device. * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The list of * secondary DNS Server IP addresses. * * @param {object} [parameters.networkInterfaceData0Settings] The 'Data 0' * network interface card settings. * * @param {string} [parameters.networkInterfaceData0Settings.controllerZeroIp] * The controller 0's IPv4 address. * * @param {string} [parameters.networkInterfaceData0Settings.controllerOneIp] * The controller 1's IPv4 address. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ configure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; configure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; configure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the list of devices for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify $expand=details to populate * additional fields related to the device or $expand=rolloverdetails to * populate additional fields related to the service data encryption key * rollover on device * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DeviceList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DeviceList>>; /** * Returns the list of devices for the specified manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify $expand=details to populate * additional fields related to the device or $expand=rolloverdetails to * populate additional fields related to the service data encryption key * rollover on device * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DeviceList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DeviceList} [result] - The deserialized result object if an error did not occur. * See {@link DeviceList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.DeviceList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.DeviceList>): void; listByManager(resourceGroupName: string, managerName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DeviceList>): void; /** * Returns the properties of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify $expand=details to populate * additional fields related to the device or $expand=rolloverdetails to * populate additional fields related to the service data encryption key * rollover on device * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Device>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Device>>; /** * Returns the properties of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] Specify $expand=details to populate * additional fields related to the device or $expand=rolloverdetails to * populate additional fields related to the service data encryption key * rollover on device * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Device} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Device} [result] - The deserialized result object if an error did not occur. * See {@link Device} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, resourceGroupName: string, managerName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Device>; get(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Device>): void; get(deviceName: string, resourceGroupName: string, managerName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Device>): void; /** * Deletes the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Patches the device. * * @param {string} deviceName The device name * * @param {object} parameters Patch representation of the device. * * @param {string} [parameters.deviceDescription] Short description given for * the device * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Device>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(deviceName: string, parameters: models.DevicePatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Device>>; /** * Patches the device. * * @param {string} deviceName The device name * * @param {object} parameters Patch representation of the device. * * @param {string} [parameters.deviceDescription] Short description given for * the device * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Device} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Device} [result] - The deserialized result object if an error did not occur. * See {@link Device} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(deviceName: string, parameters: models.DevicePatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Device>; update(deviceName: string, parameters: models.DevicePatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Device>): void; update(deviceName: string, parameters: models.DevicePatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Device>): void; /** * Authorizes the specified device for service data encryption key rollover. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ authorizeForServiceEncryptionKeyRolloverWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Authorizes the specified device for service data encryption key rollover. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ authorizeForServiceEncryptionKeyRollover(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; authorizeForServiceEncryptionKeyRollover(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; authorizeForServiceEncryptionKeyRollover(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Deactivates the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deactivateWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deactivates the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deactivate(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deactivate(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deactivate(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Downloads and installs the updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ installUpdatesWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Downloads and installs the updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ installUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; installUpdates(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; installUpdates(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns all failover sets for a given device and their eligibility for * participating in a failover. A failover set refers to a set of volume * containers that need to be failed-over as a single unit to maintain data * integrity. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FailoverSetsList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listFailoverSetsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FailoverSetsList>>; /** * Returns all failover sets for a given device and their eligibility for * participating in a failover. A failover set refers to a set of volume * containers that need to be failed-over as a single unit to maintain data * integrity. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FailoverSetsList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FailoverSetsList} [result] - The deserialized result object if an error did not occur. * See {@link FailoverSetsList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listFailoverSets(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FailoverSetsList>; listFailoverSets(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.FailoverSetsList>): void; listFailoverSets(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FailoverSetsList>): void; /** * Gets the metrics for the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricList>>; /** * Gets the metrics for the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricList} [result] - The deserialized result object if an error did not occur. * See {@link MetricList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetrics(deviceName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricList>; listMetrics(deviceName: string, resourceGroupName: string, managerName: string, filter: string, callback: ServiceCallback<models.MetricList>): void; listMetrics(deviceName: string, resourceGroupName: string, managerName: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricList>): void; /** * Gets the metric definitions for the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricDefinitionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricDefinitionWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricDefinitionList>>; /** * Gets the metric definitions for the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricDefinitionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricDefinitionList} [result] - The deserialized result object if an error did not occur. * See {@link MetricDefinitionList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricDefinitionList>; listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.MetricDefinitionList>): void; listMetricDefinition(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricDefinitionList>): void; /** * Scans for updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ scanForUpdatesWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Scans for updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ scanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; scanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; scanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Returns the update summary of the specified device name. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Updates>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getUpdateSummaryWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Updates>>; /** * Returns the update summary of the specified device name. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Updates} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Updates} [result] - The deserialized result object if an error did not occur. * See {@link Updates} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Updates>; getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Updates>): void; getUpdateSummary(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Updates>): void; /** * Failovers a set of volume containers from a specified source device to a * target device. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters FailoverRequest containing the source device and * the list of volume containers to be failed over. * * @param {string} [parameters.targetDeviceId] The ARM path ID of the device * which will act as the failover target. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers which needs to be failed-over to the target device. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ failoverWithHttpOperationResponse(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Failovers a set of volume containers from a specified source device to a * target device. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters FailoverRequest containing the source device and * the list of volume containers to be failed over. * * @param {string} [parameters.targetDeviceId] The ARM path ID of the device * which will act as the failover target. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers which needs to be failed-over to the target device. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ failover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; failover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; failover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Given a list of volume containers to be failed over from a source device, * this method returns the eligibility result, as a failover target, for all * devices under that resource. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters ListFailoverTargetsRequest containing the list of * volume containers to be failed over. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers that needs to be failed-over, for which we want to fetch * the eligible targets. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FailoverTargetsList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listFailoverTargetsWithHttpOperationResponse(sourceDeviceName: string, parameters: models.ListFailoverTargetsRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FailoverTargetsList>>; /** * Given a list of volume containers to be failed over from a source device, * this method returns the eligibility result, as a failover target, for all * devices under that resource. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters ListFailoverTargetsRequest containing the list of * volume containers to be failed over. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers that needs to be failed-over, for which we want to fetch * the eligible targets. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FailoverTargetsList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FailoverTargetsList} [result] - The deserialized result object if an error did not occur. * See {@link FailoverTargetsList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listFailoverTargets(sourceDeviceName: string, parameters: models.ListFailoverTargetsRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.FailoverTargetsList>; listFailoverTargets(sourceDeviceName: string, parameters: models.ListFailoverTargetsRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.FailoverTargetsList>): void; listFailoverTargets(sourceDeviceName: string, parameters: models.ListFailoverTargetsRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FailoverTargetsList>): void; /** * Complete minimal setup before using the device. * * @param {object} parameters The minimal properties to configure a device. * * @param {string} parameters.friendlyName The friendly name for the device. * * @param {string} parameters.currentDeviceName The current name of the device. * * @param {string} parameters.timeZone The device time zone. For eg: "Pacific * Standard Time" * * @param {object} [parameters.dnsSettings] The secondary DNS Settings of the * device. * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The list of * secondary DNS Server IP addresses. * * @param {object} [parameters.networkInterfaceData0Settings] The 'Data 0' * network interface card settings. * * @param {string} [parameters.networkInterfaceData0Settings.controllerZeroIp] * The controller 0's IPv4 address. * * @param {string} [parameters.networkInterfaceData0Settings.controllerOneIp] * The controller 1's IPv4 address. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginConfigureWithHttpOperationResponse(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Complete minimal setup before using the device. * * @param {object} parameters The minimal properties to configure a device. * * @param {string} parameters.friendlyName The friendly name for the device. * * @param {string} parameters.currentDeviceName The current name of the device. * * @param {string} parameters.timeZone The device time zone. For eg: "Pacific * Standard Time" * * @param {object} [parameters.dnsSettings] The secondary DNS Settings of the * device. * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The list of * secondary DNS Server IP addresses. * * @param {object} [parameters.networkInterfaceData0Settings] The 'Data 0' * network interface card settings. * * @param {string} [parameters.networkInterfaceData0Settings.controllerZeroIp] * The controller 0's IPv4 address. * * @param {string} [parameters.networkInterfaceData0Settings.controllerOneIp] * The controller 1's IPv4 address. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginConfigure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginConfigure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginConfigure(parameters: models.ConfigureDeviceRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Deletes the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Deactivates the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeactivateWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deactivates the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeactivate(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeactivate(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeactivate(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Downloads and installs the updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginInstallUpdatesWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Downloads and installs the updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginInstallUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginInstallUpdates(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginInstallUpdates(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Scans for updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginScanForUpdatesWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Scans for updates on the device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginScanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginScanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginScanForUpdates(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Failovers a set of volume containers from a specified source device to a * target device. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters FailoverRequest containing the source device and * the list of volume containers to be failed over. * * @param {string} [parameters.targetDeviceId] The ARM path ID of the device * which will act as the failover target. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers which needs to be failed-over to the target device. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginFailoverWithHttpOperationResponse(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Failovers a set of volume containers from a specified source device to a * target device. * * @param {string} sourceDeviceName The source device name on which failover is * performed. * * @param {object} parameters FailoverRequest containing the source device and * the list of volume containers to be failed over. * * @param {string} [parameters.targetDeviceId] The ARM path ID of the device * which will act as the failover target. * * @param {array} [parameters.volumeContainers] The list of path IDs of the * volume containers which needs to be failed-over to the target device. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginFailover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginFailover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginFailover(sourceDeviceName: string, parameters: models.FailoverRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * DeviceSettings * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface DeviceSettings { /** * Gets the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAlertSettingsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertSettings>>; /** * Gets the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertSettings} [result] - The deserialized result object if an error did not occur. * See {@link AlertSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertSettings>; getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AlertSettings>): void; getAlertSettings(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertSettings>): void; /** * Creates or updates the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The alert settings to be added or updated. * * @param {string} parameters.emailNotification Indicates whether email * notification enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.alertNotificationCulture] The alert notification * culture. * * @param {string} [parameters.notificationToServiceOwners] The value * indicating whether alert notification enabled for admin or not. Possible * values include: 'Enabled', 'Disabled' * * @param {array} [parameters.additionalRecipientEmailList] The alert * notification email list. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateAlertSettingsWithHttpOperationResponse(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertSettings>>; /** * Creates or updates the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The alert settings to be added or updated. * * @param {string} parameters.emailNotification Indicates whether email * notification enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.alertNotificationCulture] The alert notification * culture. * * @param {string} [parameters.notificationToServiceOwners] The value * indicating whether alert notification enabled for admin or not. Possible * values include: 'Enabled', 'Disabled' * * @param {array} [parameters.additionalRecipientEmailList] The alert * notification email list. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertSettings} [result] - The deserialized result object if an error did not occur. * See {@link AlertSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertSettings>; createOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AlertSettings>): void; createOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertSettings>): void; /** * Gets the network settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getNetworkSettingsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkSettings>>; /** * Gets the network settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkSettings} [result] - The deserialized result object if an error did not occur. * See {@link NetworkSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkSettings>; getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.NetworkSettings>): void; getNetworkSettings(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkSettings>): void; /** * Updates the network settings on the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The network settings to be updated. * * @param {object} [parameters.dnsSettings] The DNS (Domain Name System) * settings of device. * * @param {string} [parameters.dnsSettings.primaryDnsServer] The primary IPv4 * DNS server for the device * * @param {string} [parameters.dnsSettings.primaryIpv6DnsServer] The primary * IPv6 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The secondary * IPv4 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryIpv6DnsServers] The * secondary IPv6 DNS server for the device * * @param {object} [parameters.networkAdapters] The network adapter list of * device. * * @param {array} parameters.networkAdapters.value The value. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateNetworkSettingsWithHttpOperationResponse(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkSettings>>; /** * Updates the network settings on the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The network settings to be updated. * * @param {object} [parameters.dnsSettings] The DNS (Domain Name System) * settings of device. * * @param {string} [parameters.dnsSettings.primaryDnsServer] The primary IPv4 * DNS server for the device * * @param {string} [parameters.dnsSettings.primaryIpv6DnsServer] The primary * IPv6 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The secondary * IPv4 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryIpv6DnsServers] The * secondary IPv6 DNS server for the device * * @param {object} [parameters.networkAdapters] The network adapter list of * device. * * @param {array} parameters.networkAdapters.value The value. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkSettings} [result] - The deserialized result object if an error did not occur. * See {@link NetworkSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkSettings>; updateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.NetworkSettings>): void; updateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkSettings>): void; /** * Returns the Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecuritySettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getSecuritySettingsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecuritySettings>>; /** * Returns the Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecuritySettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecuritySettings} [result] - The deserialized result object if an error did not occur. * See {@link SecuritySettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getSecuritySettings(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecuritySettings>; getSecuritySettings(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.SecuritySettings>): void; getSecuritySettings(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecuritySettings>): void; /** * Patch Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {object} parameters The security settings properties to be patched. * * @param {object} [parameters.remoteManagementSettings] The remote management * settings. * * @param {string} parameters.remoteManagementSettings.remoteManagementMode The * remote management mode. Possible values include: 'Unknown', 'Disabled', * 'HttpsEnabled', 'HttpsAndHttpEnabled' * * @param {object} [parameters.deviceAdminPassword] The device administrator * password. * * @param {object} [parameters.snapshotPassword] The snapshot manager password. * * @param {object} [parameters.chapSettings] The device CHAP and reverse-CHAP * settings. * * @param {string} [parameters.chapSettings.initiatorUser] The CHAP initiator * user. * * @param {object} [parameters.chapSettings.initiatorSecret] The CHAP initiator * secret. * * @param {string} [parameters.chapSettings.targetUser] The CHAP target user. * * @param {object} [parameters.chapSettings.targetSecret] The target secret. * * @param {object} [parameters.cloudApplianceSettings] The cloud appliance * settings. * * @param {object} [parameters.cloudApplianceSettings.serviceDataEncryptionKey] * The service data encryption key (encrypted with DAK). * * @param {object} [parameters.cloudApplianceSettings.channelIntegrityKey] The * channel integrity key (encrypted with DAK). * * @param {string} parameters.cloudApplianceSettings.channelIntegrityKey.value * The value of the secret. * * @param {string} * [parameters.cloudApplianceSettings.channelIntegrityKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} * parameters.cloudApplianceSettings.channelIntegrityKey.encryptionAlgorithm * The algorithm used to encrypt "Value". Possible values include: 'None', * 'AES256', 'RSAES_PKCS1_v_1_5' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecuritySettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateSecuritySettingsWithHttpOperationResponse(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecuritySettings>>; /** * Patch Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {object} parameters The security settings properties to be patched. * * @param {object} [parameters.remoteManagementSettings] The remote management * settings. * * @param {string} parameters.remoteManagementSettings.remoteManagementMode The * remote management mode. Possible values include: 'Unknown', 'Disabled', * 'HttpsEnabled', 'HttpsAndHttpEnabled' * * @param {object} [parameters.deviceAdminPassword] The device administrator * password. * * @param {object} [parameters.snapshotPassword] The snapshot manager password. * * @param {object} [parameters.chapSettings] The device CHAP and reverse-CHAP * settings. * * @param {string} [parameters.chapSettings.initiatorUser] The CHAP initiator * user. * * @param {object} [parameters.chapSettings.initiatorSecret] The CHAP initiator * secret. * * @param {string} [parameters.chapSettings.targetUser] The CHAP target user. * * @param {object} [parameters.chapSettings.targetSecret] The target secret. * * @param {object} [parameters.cloudApplianceSettings] The cloud appliance * settings. * * @param {object} [parameters.cloudApplianceSettings.serviceDataEncryptionKey] * The service data encryption key (encrypted with DAK). * * @param {object} [parameters.cloudApplianceSettings.channelIntegrityKey] The * channel integrity key (encrypted with DAK). * * @param {string} parameters.cloudApplianceSettings.channelIntegrityKey.value * The value of the secret. * * @param {string} * [parameters.cloudApplianceSettings.channelIntegrityKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} * parameters.cloudApplianceSettings.channelIntegrityKey.encryptionAlgorithm * The algorithm used to encrypt "Value". Possible values include: 'None', * 'AES256', 'RSAES_PKCS1_v_1_5' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecuritySettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecuritySettings} [result] - The deserialized result object if an error did not occur. * See {@link SecuritySettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ updateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecuritySettings>; updateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.SecuritySettings>): void; updateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecuritySettings>): void; /** * sync Remote management Certificate between appliance and Service * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ syncRemotemanagementCertificateWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * sync Remote management Certificate between appliance and Service * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ syncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; syncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; syncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets the time settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TimeSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getTimeSettingsWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TimeSettings>>; /** * Gets the time settings of the specified device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TimeSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TimeSettings} [result] - The deserialized result object if an error did not occur. * See {@link TimeSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TimeSettings>; getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.TimeSettings>): void; getTimeSettings(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TimeSettings>): void; /** * Creates or updates the time settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The time settings to be added or updated. * * @param {string} parameters.timeZone The timezone of device, like '(UTC * -06:00) Central America' * * @param {string} [parameters.primaryTimeServer] The primary Network Time * Protocol (NTP) server name, like 'time.windows.com'. * * @param {array} [parameters.secondaryTimeServer] The secondary Network Time * Protocol (NTP) server name, like 'time.contoso.com'. It's optional. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TimeSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateTimeSettingsWithHttpOperationResponse(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TimeSettings>>; /** * Creates or updates the time settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The time settings to be added or updated. * * @param {string} parameters.timeZone The timezone of device, like '(UTC * -06:00) Central America' * * @param {string} [parameters.primaryTimeServer] The primary Network Time * Protocol (NTP) server name, like 'time.windows.com'. * * @param {array} [parameters.secondaryTimeServer] The secondary Network Time * Protocol (NTP) server name, like 'time.contoso.com'. It's optional. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TimeSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TimeSettings} [result] - The deserialized result object if an error did not occur. * See {@link TimeSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TimeSettings>; createOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.TimeSettings>): void; createOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TimeSettings>): void; /** * Creates or updates the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The alert settings to be added or updated. * * @param {string} parameters.emailNotification Indicates whether email * notification enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.alertNotificationCulture] The alert notification * culture. * * @param {string} [parameters.notificationToServiceOwners] The value * indicating whether alert notification enabled for admin or not. Possible * values include: 'Enabled', 'Disabled' * * @param {array} [parameters.additionalRecipientEmailList] The alert * notification email list. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AlertSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateAlertSettingsWithHttpOperationResponse(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AlertSettings>>; /** * Creates or updates the alert settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The alert settings to be added or updated. * * @param {string} parameters.emailNotification Indicates whether email * notification enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.alertNotificationCulture] The alert notification * culture. * * @param {string} [parameters.notificationToServiceOwners] The value * indicating whether alert notification enabled for admin or not. Possible * values include: 'Enabled', 'Disabled' * * @param {array} [parameters.additionalRecipientEmailList] The alert * notification email list. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {AlertSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {AlertSettings} [result] - The deserialized result object if an error did not occur. * See {@link AlertSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AlertSettings>; beginCreateOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.AlertSettings>): void; beginCreateOrUpdateAlertSettings(deviceName: string, parameters: models.AlertSettings, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AlertSettings>): void; /** * Updates the network settings on the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The network settings to be updated. * * @param {object} [parameters.dnsSettings] The DNS (Domain Name System) * settings of device. * * @param {string} [parameters.dnsSettings.primaryDnsServer] The primary IPv4 * DNS server for the device * * @param {string} [parameters.dnsSettings.primaryIpv6DnsServer] The primary * IPv6 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The secondary * IPv4 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryIpv6DnsServers] The * secondary IPv6 DNS server for the device * * @param {object} [parameters.networkAdapters] The network adapter list of * device. * * @param {array} parameters.networkAdapters.value The value. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateNetworkSettingsWithHttpOperationResponse(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkSettings>>; /** * Updates the network settings on the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The network settings to be updated. * * @param {object} [parameters.dnsSettings] The DNS (Domain Name System) * settings of device. * * @param {string} [parameters.dnsSettings.primaryDnsServer] The primary IPv4 * DNS server for the device * * @param {string} [parameters.dnsSettings.primaryIpv6DnsServer] The primary * IPv6 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryDnsServers] The secondary * IPv4 DNS server for the device * * @param {array} [parameters.dnsSettings.secondaryIpv6DnsServers] The * secondary IPv6 DNS server for the device * * @param {object} [parameters.networkAdapters] The network adapter list of * device. * * @param {array} parameters.networkAdapters.value The value. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkSettings} [result] - The deserialized result object if an error did not occur. * See {@link NetworkSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkSettings>; beginUpdateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.NetworkSettings>): void; beginUpdateNetworkSettings(deviceName: string, parameters: models.NetworkSettingsPatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkSettings>): void; /** * Patch Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {object} parameters The security settings properties to be patched. * * @param {object} [parameters.remoteManagementSettings] The remote management * settings. * * @param {string} parameters.remoteManagementSettings.remoteManagementMode The * remote management mode. Possible values include: 'Unknown', 'Disabled', * 'HttpsEnabled', 'HttpsAndHttpEnabled' * * @param {object} [parameters.deviceAdminPassword] The device administrator * password. * * @param {object} [parameters.snapshotPassword] The snapshot manager password. * * @param {object} [parameters.chapSettings] The device CHAP and reverse-CHAP * settings. * * @param {string} [parameters.chapSettings.initiatorUser] The CHAP initiator * user. * * @param {object} [parameters.chapSettings.initiatorSecret] The CHAP initiator * secret. * * @param {string} [parameters.chapSettings.targetUser] The CHAP target user. * * @param {object} [parameters.chapSettings.targetSecret] The target secret. * * @param {object} [parameters.cloudApplianceSettings] The cloud appliance * settings. * * @param {object} [parameters.cloudApplianceSettings.serviceDataEncryptionKey] * The service data encryption key (encrypted with DAK). * * @param {object} [parameters.cloudApplianceSettings.channelIntegrityKey] The * channel integrity key (encrypted with DAK). * * @param {string} parameters.cloudApplianceSettings.channelIntegrityKey.value * The value of the secret. * * @param {string} * [parameters.cloudApplianceSettings.channelIntegrityKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} * parameters.cloudApplianceSettings.channelIntegrityKey.encryptionAlgorithm * The algorithm used to encrypt "Value". Possible values include: 'None', * 'AES256', 'RSAES_PKCS1_v_1_5' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecuritySettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateSecuritySettingsWithHttpOperationResponse(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecuritySettings>>; /** * Patch Security properties of the specified device name. * * @param {string} deviceName The device name * * @param {object} parameters The security settings properties to be patched. * * @param {object} [parameters.remoteManagementSettings] The remote management * settings. * * @param {string} parameters.remoteManagementSettings.remoteManagementMode The * remote management mode. Possible values include: 'Unknown', 'Disabled', * 'HttpsEnabled', 'HttpsAndHttpEnabled' * * @param {object} [parameters.deviceAdminPassword] The device administrator * password. * * @param {object} [parameters.snapshotPassword] The snapshot manager password. * * @param {object} [parameters.chapSettings] The device CHAP and reverse-CHAP * settings. * * @param {string} [parameters.chapSettings.initiatorUser] The CHAP initiator * user. * * @param {object} [parameters.chapSettings.initiatorSecret] The CHAP initiator * secret. * * @param {string} [parameters.chapSettings.targetUser] The CHAP target user. * * @param {object} [parameters.chapSettings.targetSecret] The target secret. * * @param {object} [parameters.cloudApplianceSettings] The cloud appliance * settings. * * @param {object} [parameters.cloudApplianceSettings.serviceDataEncryptionKey] * The service data encryption key (encrypted with DAK). * * @param {object} [parameters.cloudApplianceSettings.channelIntegrityKey] The * channel integrity key (encrypted with DAK). * * @param {string} parameters.cloudApplianceSettings.channelIntegrityKey.value * The value of the secret. * * @param {string} * [parameters.cloudApplianceSettings.channelIntegrityKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} * parameters.cloudApplianceSettings.channelIntegrityKey.encryptionAlgorithm * The algorithm used to encrypt "Value". Possible values include: 'None', * 'AES256', 'RSAES_PKCS1_v_1_5' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecuritySettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecuritySettings} [result] - The deserialized result object if an error did not occur. * See {@link SecuritySettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecuritySettings>; beginUpdateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.SecuritySettings>): void; beginUpdateSecuritySettings(deviceName: string, parameters: models.SecuritySettingsPatch, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecuritySettings>): void; /** * sync Remote management Certificate between appliance and Service * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginSyncRemotemanagementCertificateWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * sync Remote management Certificate between appliance and Service * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginSyncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginSyncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginSyncRemotemanagementCertificate(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or updates the time settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The time settings to be added or updated. * * @param {string} parameters.timeZone The timezone of device, like '(UTC * -06:00) Central America' * * @param {string} [parameters.primaryTimeServer] The primary Network Time * Protocol (NTP) server name, like 'time.windows.com'. * * @param {array} [parameters.secondaryTimeServer] The secondary Network Time * Protocol (NTP) server name, like 'time.contoso.com'. It's optional. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TimeSettings>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateTimeSettingsWithHttpOperationResponse(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TimeSettings>>; /** * Creates or updates the time settings of the specified device. * * @param {string} deviceName The device name * * @param {object} parameters The time settings to be added or updated. * * @param {string} parameters.timeZone The timezone of device, like '(UTC * -06:00) Central America' * * @param {string} [parameters.primaryTimeServer] The primary Network Time * Protocol (NTP) server name, like 'time.windows.com'. * * @param {array} [parameters.secondaryTimeServer] The secondary Network Time * Protocol (NTP) server name, like 'time.contoso.com'. It's optional. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TimeSettings} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TimeSettings} [result] - The deserialized result object if an error did not occur. * See {@link TimeSettings} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TimeSettings>; beginCreateOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.TimeSettings>): void; beginCreateOrUpdateTimeSettings(deviceName: string, parameters: models.TimeSettings, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TimeSettings>): void; } /** * @class * BackupPolicies * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface BackupPolicies { /** * Gets all the backup policies in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupPolicyList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupPolicyList>>; /** * Gets all the backup policies in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupPolicyList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupPolicyList} [result] - The deserialized result object if an error did not occur. * See {@link BackupPolicyList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupPolicyList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupPolicyList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupPolicyList>): void; /** * Gets the properties of the specified backup policy name. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of backup policy to be fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupPolicy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupPolicy>>; /** * Gets the properties of the specified backup policy name. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of backup policy to be fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupPolicy} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupPolicy} [result] - The deserialized result object if an error did not occur. * See {@link BackupPolicy} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupPolicy>; get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupPolicy>): void; get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupPolicy>): void; /** * Creates or updates the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy to be * created/updated. * * @param {object} parameters The backup policy. * * @param {array} parameters.volumeIds The path IDs of the volumes which are * part of the backup policy. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupPolicy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupPolicy>>; /** * Creates or updates the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy to be * created/updated. * * @param {object} parameters The backup policy. * * @param {array} parameters.volumeIds The path IDs of the volumes which are * part of the backup policy. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupPolicy} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupPolicy} [result] - The deserialized result object if an error did not occur. * See {@link BackupPolicy} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupPolicy>; createOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupPolicy>): void; createOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupPolicy>): void; /** * Deletes the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Backup the backup policy now. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupType The backup Type. This can be cloudSnapshot or * localSnapshot. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ backupNowWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Backup the backup policy now. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupType The backup Type. This can be cloudSnapshot or * localSnapshot. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ backupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; backupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; backupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or updates the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy to be * created/updated. * * @param {object} parameters The backup policy. * * @param {array} parameters.volumeIds The path IDs of the volumes which are * part of the backup policy. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupPolicy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupPolicy>>; /** * Creates or updates the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy to be * created/updated. * * @param {object} parameters The backup policy. * * @param {array} parameters.volumeIds The path IDs of the volumes which are * part of the backup policy. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupPolicy} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupPolicy} [result] - The deserialized result object if an error did not occur. * See {@link BackupPolicy} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupPolicy>; beginCreateOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupPolicy>): void; beginCreateOrUpdate(deviceName: string, backupPolicyName: string, parameters: models.BackupPolicy, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupPolicy>): void; /** * Deletes the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The name of the backup policy. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Backup the backup policy now. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupType The backup Type. This can be cloudSnapshot or * localSnapshot. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginBackupNowWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Backup the backup policy now. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupType The backup Type. This can be cloudSnapshot or * localSnapshot. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginBackupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginBackupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginBackupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * BackupSchedules * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface BackupSchedules { /** * Gets all the backup schedules in a backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupScheduleList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBackupPolicyWithHttpOperationResponse(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupScheduleList>>; /** * Gets all the backup schedules in a backup policy. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupScheduleList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupScheduleList} [result] - The deserialized result object if an error did not occur. * See {@link BackupScheduleList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupScheduleList>; listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupScheduleList>): void; listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupScheduleList>): void; /** * Gets the properties of the specified backup schedule name. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name of the backup schedule to be * fetched * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupSchedule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupSchedule>>; /** * Gets the properties of the specified backup schedule name. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name of the backup schedule to be * fetched * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupSchedule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupSchedule} [result] - The deserialized result object if an error did not occur. * See {@link BackupSchedule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupSchedule>; get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupSchedule>): void; get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupSchedule>): void; /** * Creates or updates the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The backup schedule name. * * @param {object} parameters The backup schedule. * * @param {object} parameters.scheduleRecurrence The schedule recurrence. * * @param {string} parameters.scheduleRecurrence.recurrenceType The recurrence * type. Possible values include: 'Minutes', 'Hourly', 'Daily', 'Weekly' * * @param {number} parameters.scheduleRecurrence.recurrenceValue The recurrence * value. * * @param {array} [parameters.scheduleRecurrence.weeklyDaysList] The week days * list. Applicable only for schedules of recurrence type 'weekly'. * * @param {string} parameters.backupType The type of backup which needs to be * taken. Possible values include: 'LocalSnapshot', 'CloudSnapshot' * * @param {number} parameters.retentionCount The number of backups to be * retained. * * @param {date} parameters.startTime The start time of the schedule. * * @param {string} parameters.scheduleStatus The schedule status. Possible * values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupSchedule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupSchedule>>; /** * Creates or updates the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The backup schedule name. * * @param {object} parameters The backup schedule. * * @param {object} parameters.scheduleRecurrence The schedule recurrence. * * @param {string} parameters.scheduleRecurrence.recurrenceType The recurrence * type. Possible values include: 'Minutes', 'Hourly', 'Daily', 'Weekly' * * @param {number} parameters.scheduleRecurrence.recurrenceValue The recurrence * value. * * @param {array} [parameters.scheduleRecurrence.weeklyDaysList] The week days * list. Applicable only for schedules of recurrence type 'weekly'. * * @param {string} parameters.backupType The type of backup which needs to be * taken. Possible values include: 'LocalSnapshot', 'CloudSnapshot' * * @param {number} parameters.retentionCount The number of backups to be * retained. * * @param {date} parameters.startTime The start time of the schedule. * * @param {string} parameters.scheduleStatus The schedule status. Possible * values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupSchedule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupSchedule} [result] - The deserialized result object if an error did not occur. * See {@link BackupSchedule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupSchedule>; createOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupSchedule>): void; createOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupSchedule>): void; /** * Deletes the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name the backup schedule. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name the backup schedule. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or updates the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The backup schedule name. * * @param {object} parameters The backup schedule. * * @param {object} parameters.scheduleRecurrence The schedule recurrence. * * @param {string} parameters.scheduleRecurrence.recurrenceType The recurrence * type. Possible values include: 'Minutes', 'Hourly', 'Daily', 'Weekly' * * @param {number} parameters.scheduleRecurrence.recurrenceValue The recurrence * value. * * @param {array} [parameters.scheduleRecurrence.weeklyDaysList] The week days * list. Applicable only for schedules of recurrence type 'weekly'. * * @param {string} parameters.backupType The type of backup which needs to be * taken. Possible values include: 'LocalSnapshot', 'CloudSnapshot' * * @param {number} parameters.retentionCount The number of backups to be * retained. * * @param {date} parameters.startTime The start time of the schedule. * * @param {string} parameters.scheduleStatus The schedule status. Possible * values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupSchedule>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupSchedule>>; /** * Creates or updates the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The backup schedule name. * * @param {object} parameters The backup schedule. * * @param {object} parameters.scheduleRecurrence The schedule recurrence. * * @param {string} parameters.scheduleRecurrence.recurrenceType The recurrence * type. Possible values include: 'Minutes', 'Hourly', 'Daily', 'Weekly' * * @param {number} parameters.scheduleRecurrence.recurrenceValue The recurrence * value. * * @param {array} [parameters.scheduleRecurrence.weeklyDaysList] The week days * list. Applicable only for schedules of recurrence type 'weekly'. * * @param {string} parameters.backupType The type of backup which needs to be * taken. Possible values include: 'LocalSnapshot', 'CloudSnapshot' * * @param {number} parameters.retentionCount The number of backups to be * retained. * * @param {date} parameters.startTime The start time of the schedule. * * @param {string} parameters.scheduleStatus The schedule status. Possible * values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupSchedule} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupSchedule} [result] - The deserialized result object if an error did not occur. * See {@link BackupSchedule} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupSchedule>; beginCreateOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupSchedule>): void; beginCreateOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: models.BackupSchedule, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupSchedule>): void; /** * Deletes the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name the backup schedule. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup schedule. * * @param {string} deviceName The device name * * @param {string} backupPolicyName The backup policy name. * * @param {string} backupScheduleName The name the backup schedule. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Backups * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Backups { /** * Retrieves all the backups in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupList>>; /** * Retrieves all the backups in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupList} [result] - The deserialized result object if an error did not occur. * See {@link BackupList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.BackupList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupList>): void; /** * Deletes the backup. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Clones the backup element as a new volume. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} backupElementName The backup element name. * * @param {object} parameters The clone request object. * * @param {string} parameters.targetDeviceId The path ID of the device which * will act as the clone target. * * @param {string} parameters.targetVolumeName The name of the new volume which * will be created and the backup will be cloned into. * * @param {array} parameters.targetAccessControlRecordIds The list of path IDs * of the access control records to be associated to the new cloned volume. * * @param {object} parameters.backupElement The backup element that is cloned. * * @param {string} parameters.backupElement.elementId The path ID that uniquely * identifies the backup element. * * @param {string} parameters.backupElement.elementName The name of the backup * element. * * @param {string} parameters.backupElement.elementType The hierarchical type * of the backup element. * * @param {number} parameters.backupElement.sizeInBytes The size in bytes. * * @param {string} parameters.backupElement.volumeName The name of the volume. * * @param {string} parameters.backupElement.volumeContainerId The path ID of * the volume container. * * @param {string} [parameters.backupElement.volumeType] The volume type. * Possible values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cloneWithHttpOperationResponse(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Clones the backup element as a new volume. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} backupElementName The backup element name. * * @param {object} parameters The clone request object. * * @param {string} parameters.targetDeviceId The path ID of the device which * will act as the clone target. * * @param {string} parameters.targetVolumeName The name of the new volume which * will be created and the backup will be cloned into. * * @param {array} parameters.targetAccessControlRecordIds The list of path IDs * of the access control records to be associated to the new cloned volume. * * @param {object} parameters.backupElement The backup element that is cloned. * * @param {string} parameters.backupElement.elementId The path ID that uniquely * identifies the backup element. * * @param {string} parameters.backupElement.elementName The name of the backup * element. * * @param {string} parameters.backupElement.elementType The hierarchical type * of the backup element. * * @param {number} parameters.backupElement.sizeInBytes The size in bytes. * * @param {string} parameters.backupElement.volumeName The name of the volume. * * @param {string} parameters.backupElement.volumeContainerId The path ID of * the volume container. * * @param {string} [parameters.backupElement.volumeType] The volume type. * Possible values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ clone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; clone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; clone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Restores the backup on the device. * * @param {string} deviceName The device name * * @param {string} backupName The backupSet name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ restoreWithHttpOperationResponse(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Restores the backup on the device. * * @param {string} deviceName The device name * * @param {string} backupName The backupSet name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ restore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; restore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; restore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Deletes the backup. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the backup. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Clones the backup element as a new volume. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} backupElementName The backup element name. * * @param {object} parameters The clone request object. * * @param {string} parameters.targetDeviceId The path ID of the device which * will act as the clone target. * * @param {string} parameters.targetVolumeName The name of the new volume which * will be created and the backup will be cloned into. * * @param {array} parameters.targetAccessControlRecordIds The list of path IDs * of the access control records to be associated to the new cloned volume. * * @param {object} parameters.backupElement The backup element that is cloned. * * @param {string} parameters.backupElement.elementId The path ID that uniquely * identifies the backup element. * * @param {string} parameters.backupElement.elementName The name of the backup * element. * * @param {string} parameters.backupElement.elementType The hierarchical type * of the backup element. * * @param {number} parameters.backupElement.sizeInBytes The size in bytes. * * @param {string} parameters.backupElement.volumeName The name of the volume. * * @param {string} parameters.backupElement.volumeContainerId The path ID of * the volume container. * * @param {string} [parameters.backupElement.volumeType] The volume type. * Possible values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCloneWithHttpOperationResponse(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Clones the backup element as a new volume. * * @param {string} deviceName The device name * * @param {string} backupName The backup name. * * @param {string} backupElementName The backup element name. * * @param {object} parameters The clone request object. * * @param {string} parameters.targetDeviceId The path ID of the device which * will act as the clone target. * * @param {string} parameters.targetVolumeName The name of the new volume which * will be created and the backup will be cloned into. * * @param {array} parameters.targetAccessControlRecordIds The list of path IDs * of the access control records to be associated to the new cloned volume. * * @param {object} parameters.backupElement The backup element that is cloned. * * @param {string} parameters.backupElement.elementId The path ID that uniquely * identifies the backup element. * * @param {string} parameters.backupElement.elementName The name of the backup * element. * * @param {string} parameters.backupElement.elementType The hierarchical type * of the backup element. * * @param {number} parameters.backupElement.sizeInBytes The size in bytes. * * @param {string} parameters.backupElement.volumeName The name of the volume. * * @param {string} parameters.backupElement.volumeContainerId The path ID of * the volume container. * * @param {string} [parameters.backupElement.volumeType] The volume type. * Possible values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginClone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginClone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginClone(deviceName: string, backupName: string, backupElementName: string, parameters: models.CloneRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Restores the backup on the device. * * @param {string} deviceName The device name * * @param {string} backupName The backupSet name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginRestoreWithHttpOperationResponse(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Restores the backup on the device. * * @param {string} deviceName The device name * * @param {string} backupName The backupSet name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginRestore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginRestore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginRestore(deviceName: string, backupName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Retrieves all the backups in a device. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BackupList>>; /** * Retrieves all the backups in a device. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BackupList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BackupList} [result] - The deserialized result object if an error did not occur. * See {@link BackupList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDeviceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BackupList>; listByDeviceNext(nextPageLink: string, callback: ServiceCallback<models.BackupList>): void; listByDeviceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BackupList>): void; } /** * @class * HardwareComponentGroups * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface HardwareComponentGroups { /** * Lists the hardware component groups at device-level. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<HardwareComponentGroupList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.HardwareComponentGroupList>>; /** * Lists the hardware component groups at device-level. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {HardwareComponentGroupList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {HardwareComponentGroupList} [result] - The deserialized result object if an error did not occur. * See {@link HardwareComponentGroupList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.HardwareComponentGroupList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.HardwareComponentGroupList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.HardwareComponentGroupList>): void; /** * Changes the power state of the controller. * * @param {string} deviceName The device name * * @param {string} hardwareComponentGroupName The hardware component group * name. * * @param {object} parameters The controller power state change request. * * @param {string} parameters.action The power state that the request is * expecting for the controller of the device. Possible values include: * 'Start', 'Restart', 'Shutdown' * * @param {string} parameters.activeController The active controller that the * request is expecting on the device. Possible values include: 'Unknown', * 'None', 'Controller0', 'Controller1' * * @param {string} parameters.controller0State The controller 0's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} parameters.controller1State The controller 1's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ changeControllerPowerStateWithHttpOperationResponse(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Changes the power state of the controller. * * @param {string} deviceName The device name * * @param {string} hardwareComponentGroupName The hardware component group * name. * * @param {object} parameters The controller power state change request. * * @param {string} parameters.action The power state that the request is * expecting for the controller of the device. Possible values include: * 'Start', 'Restart', 'Shutdown' * * @param {string} parameters.activeController The active controller that the * request is expecting on the device. Possible values include: 'Unknown', * 'None', 'Controller0', 'Controller1' * * @param {string} parameters.controller0State The controller 0's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} parameters.controller1State The controller 1's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ changeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; changeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; changeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Changes the power state of the controller. * * @param {string} deviceName The device name * * @param {string} hardwareComponentGroupName The hardware component group * name. * * @param {object} parameters The controller power state change request. * * @param {string} parameters.action The power state that the request is * expecting for the controller of the device. Possible values include: * 'Start', 'Restart', 'Shutdown' * * @param {string} parameters.activeController The active controller that the * request is expecting on the device. Possible values include: 'Unknown', * 'None', 'Controller0', 'Controller1' * * @param {string} parameters.controller0State The controller 0's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} parameters.controller1State The controller 1's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginChangeControllerPowerStateWithHttpOperationResponse(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Changes the power state of the controller. * * @param {string} deviceName The device name * * @param {string} hardwareComponentGroupName The hardware component group * name. * * @param {object} parameters The controller power state change request. * * @param {string} parameters.action The power state that the request is * expecting for the controller of the device. Possible values include: * 'Start', 'Restart', 'Shutdown' * * @param {string} parameters.activeController The active controller that the * request is expecting on the device. Possible values include: 'Unknown', * 'None', 'Controller0', 'Controller1' * * @param {string} parameters.controller0State The controller 0's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} parameters.controller1State The controller 1's status that * the request is expecting on the device. Possible values include: * 'NotPresent', 'PoweredOff', 'Ok', 'Recovering', 'Warning', 'Failure' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginChangeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginChangeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginChangeControllerPowerState(deviceName: string, hardwareComponentGroupName: string, parameters: models.ControllerPowerStateChangeRequest, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Jobs * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Jobs { /** * Gets all the jobs for specified device. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobList>>; /** * Gets all the jobs for specified device. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {JobList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {JobList} [result] - The deserialized result object if an error did not occur. * See {@link JobList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.JobList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.JobList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobList>): void; /** * Gets the details of the specified job name. * * @param {string} deviceName The device name * * @param {string} jobName The job Name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * Gets the details of the specified job name. * * @param {string} deviceName The device name * * @param {string} jobName The job Name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Job} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; get(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Job>): void; get(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * Cancels a job on the device. * * @param {string} deviceName The device name * * @param {string} jobName The jobName. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ cancelWithHttpOperationResponse(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Cancels a job on the device. * * @param {string} deviceName The device name * * @param {string} jobName The jobName. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ cancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; cancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; cancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets all the jobs for the specified manager. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobList>>; /** * Gets all the jobs for the specified manager. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData Filter options * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {JobList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {JobList} [result] - The deserialized result object if an error did not occur. * See {@link JobList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.JobList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.JobList>): void; listByManager(resourceGroupName: string, managerName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobList>): void; /** * Cancels a job on the device. * * @param {string} deviceName The device name * * @param {string} jobName The jobName. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCancelWithHttpOperationResponse(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Cancels a job on the device. * * @param {string} deviceName The device name * * @param {string} jobName The jobName. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginCancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginCancel(deviceName: string, jobName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets all the jobs for specified device. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobList>>; /** * Gets all the jobs for specified device. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {JobList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {JobList} [result] - The deserialized result object if an error did not occur. * See {@link JobList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDeviceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JobList>; listByDeviceNext(nextPageLink: string, callback: ServiceCallback<models.JobList>): void; listByDeviceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobList>): void; /** * Gets all the jobs for the specified manager. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobList>>; /** * Gets all the jobs for the specified manager. With optional OData query * parameters, a filtered set of jobs is returned. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {JobList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {JobList} [result] - The deserialized result object if an error did not occur. * See {@link JobList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagerNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.JobList>; listByManagerNext(nextPageLink: string, callback: ServiceCallback<models.JobList>): void; listByManagerNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobList>): void; } /** * @class * VolumeContainers * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface VolumeContainers { /** * Gets all the volume containers in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeContainerList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeContainerList>>; /** * Gets all the volume containers in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeContainerList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeContainerList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeContainerList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeContainerList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeContainerList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeContainerList>): void; /** * Gets the properties of the specified volume container name. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeContainer>>; /** * Gets the properties of the specified volume container name. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeContainer} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeContainer} [result] - The deserialized result object if an error did not occur. * See {@link VolumeContainer} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeContainer>; get(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeContainer>): void; get(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeContainer>): void; /** * Creates or updates the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {object} parameters The volume container to be added or updated. * * @param {object} [parameters.encryptionKey] The key used to encrypt data in * the volume container. It is required when property 'EncryptionStatus' is * "Enabled". * * @param {string} parameters.encryptionKey.value The value of the secret. * * @param {string} [parameters.encryptionKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} parameters.encryptionKey.encryptionAlgorithm The algorithm * used to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} parameters.storageAccountCredentialId The path ID of storage * account associated with the volume container. * * @param {number} [parameters.bandWidthRateInMbps] The bandwidth-rate set on * the volume container. * * @param {string} [parameters.bandwidthSettingId] The ID of the bandwidth * setting associated with the volume container. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeContainer>>; /** * Creates or updates the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {object} parameters The volume container to be added or updated. * * @param {object} [parameters.encryptionKey] The key used to encrypt data in * the volume container. It is required when property 'EncryptionStatus' is * "Enabled". * * @param {string} parameters.encryptionKey.value The value of the secret. * * @param {string} [parameters.encryptionKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} parameters.encryptionKey.encryptionAlgorithm The algorithm * used to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} parameters.storageAccountCredentialId The path ID of storage * account associated with the volume container. * * @param {number} [parameters.bandWidthRateInMbps] The bandwidth-rate set on * the volume container. * * @param {string} [parameters.bandwidthSettingId] The ID of the bandwidth * setting associated with the volume container. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeContainer} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeContainer} [result] - The deserialized result object if an error did not occur. * See {@link VolumeContainer} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeContainer>; createOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeContainer>): void; createOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeContainer>): void; /** * Deletes the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets the metrics for the specified volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricsWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricList>>; /** * Gets the metrics for the specified volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricList} [result] - The deserialized result object if an error did not occur. * See {@link MetricList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetrics(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricList>; listMetrics(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, filter: string, callback: ServiceCallback<models.MetricList>): void; listMetrics(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricList>): void; /** * Gets the metric definitions for the specified volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricDefinitionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricDefinitionWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricDefinitionList>>; /** * Gets the metric definitions for the specified volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricDefinitionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricDefinitionList} [result] - The deserialized result object if an error did not occur. * See {@link MetricDefinitionList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetricDefinition(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricDefinitionList>; listMetricDefinition(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.MetricDefinitionList>): void; listMetricDefinition(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricDefinitionList>): void; /** * Creates or updates the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {object} parameters The volume container to be added or updated. * * @param {object} [parameters.encryptionKey] The key used to encrypt data in * the volume container. It is required when property 'EncryptionStatus' is * "Enabled". * * @param {string} parameters.encryptionKey.value The value of the secret. * * @param {string} [parameters.encryptionKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} parameters.encryptionKey.encryptionAlgorithm The algorithm * used to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} parameters.storageAccountCredentialId The path ID of storage * account associated with the volume container. * * @param {number} [parameters.bandWidthRateInMbps] The bandwidth-rate set on * the volume container. * * @param {string} [parameters.bandwidthSettingId] The ID of the bandwidth * setting associated with the volume container. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeContainer>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeContainer>>; /** * Creates or updates the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {object} parameters The volume container to be added or updated. * * @param {object} [parameters.encryptionKey] The key used to encrypt data in * the volume container. It is required when property 'EncryptionStatus' is * "Enabled". * * @param {string} parameters.encryptionKey.value The value of the secret. * * @param {string} [parameters.encryptionKey.encryptionCertThumbprint] * Thumbprint certificate that was used to encrypt "Value". If the value in * unencrypted, it will be null. * * @param {string} parameters.encryptionKey.encryptionAlgorithm The algorithm * used to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} parameters.storageAccountCredentialId The path ID of storage * account associated with the volume container. * * @param {number} [parameters.bandWidthRateInMbps] The bandwidth-rate set on * the volume container. * * @param {string} [parameters.bandwidthSettingId] The ID of the bandwidth * setting associated with the volume container. * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeContainer} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeContainer} [result] - The deserialized result object if an error did not occur. * See {@link VolumeContainer} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeContainer>; beginCreateOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeContainer>): void; beginCreateOrUpdate(deviceName: string, volumeContainerName: string, parameters: models.VolumeContainer, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeContainer>): void; /** * Deletes the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The name of the volume container. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Volumes * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface Volumes { /** * Retrieves all the volumes in a volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByVolumeContainerWithHttpOperationResponse(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeList>>; /** * Retrieves all the volumes in a volume container. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByVolumeContainer(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeList>; listByVolumeContainer(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeList>): void; listByVolumeContainer(deviceName: string, volumeContainerName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeList>): void; /** * Returns the properties of the specified volume name. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Volume>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Volume>>; /** * Returns the properties of the specified volume name. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Volume} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Volume} [result] - The deserialized result object if an error did not occur. * See {@link Volume} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Volume>; get(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Volume>): void; get(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Volume>): void; /** * Creates or updates the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {object} parameters Volume to be created or updated. * * @param {number} parameters.sizeInBytes The size of the volume in bytes. * * @param {string} parameters.volumeType The type of the volume. Possible * values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {array} parameters.accessControlRecordIds The IDs of the access * control records, associated with the volume. * * @param {string} parameters.volumeStatus The volume status. Possible values * include: 'Online', 'Offline' * * @param {string} parameters.monitoringStatus The monitoring status of the * volume. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Volume>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Volume>>; /** * Creates or updates the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {object} parameters Volume to be created or updated. * * @param {number} parameters.sizeInBytes The size of the volume in bytes. * * @param {string} parameters.volumeType The type of the volume. Possible * values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {array} parameters.accessControlRecordIds The IDs of the access * control records, associated with the volume. * * @param {string} parameters.volumeStatus The volume status. Possible values * include: 'Online', 'Offline' * * @param {string} parameters.monitoringStatus The monitoring status of the * volume. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Volume} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Volume} [result] - The deserialized result object if an error did not occur. * See {@link Volume} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Volume>; createOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Volume>): void; createOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Volume>): void; /** * Deletes the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets the metrics for the specified volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricsWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricList>>; /** * Gets the metrics for the specified volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {string} filter OData Filter options * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricList} [result] - The deserialized result object if an error did not occur. * See {@link MetricList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetrics(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricList>; listMetrics(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, filter: string, callback: ServiceCallback<models.MetricList>): void; listMetrics(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricList>): void; /** * Gets the metric definitions for the specified volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MetricDefinitionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listMetricDefinitionWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MetricDefinitionList>>; /** * Gets the metric definitions for the specified volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MetricDefinitionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MetricDefinitionList} [result] - The deserialized result object if an error did not occur. * See {@link MetricDefinitionList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listMetricDefinition(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MetricDefinitionList>; listMetricDefinition(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.MetricDefinitionList>): void; listMetricDefinition(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MetricDefinitionList>): void; /** * Retrieves all the volumes in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDeviceWithHttpOperationResponse(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeList>>; /** * Retrieves all the volumes in a device. * * @param {string} deviceName The device name * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeList>; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.VolumeList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeList>): void; /** * Creates or updates the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {object} parameters Volume to be created or updated. * * @param {number} parameters.sizeInBytes The size of the volume in bytes. * * @param {string} parameters.volumeType The type of the volume. Possible * values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {array} parameters.accessControlRecordIds The IDs of the access * control records, associated with the volume. * * @param {string} parameters.volumeStatus The volume status. Possible values * include: 'Online', 'Offline' * * @param {string} parameters.monitoringStatus The monitoring status of the * volume. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Volume>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Volume>>; /** * Creates or updates the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {object} parameters Volume to be created or updated. * * @param {number} parameters.sizeInBytes The size of the volume in bytes. * * @param {string} parameters.volumeType The type of the volume. Possible * values include: 'Tiered', 'Archival', 'LocallyPinned' * * @param {array} parameters.accessControlRecordIds The IDs of the access * control records, associated with the volume. * * @param {string} parameters.volumeStatus The volume status. Possible values * include: 'Online', 'Offline' * * @param {string} parameters.monitoringStatus The monitoring status of the * volume. Possible values include: 'Enabled', 'Disabled' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Volume} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Volume} [result] - The deserialized result object if an error did not occur. * See {@link Volume} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Volume>; beginCreateOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.Volume>): void; beginCreateOrUpdate(deviceName: string, volumeContainerName: string, volumeName: string, parameters: models.Volume, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Volume>): void; /** * Deletes the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the volume. * * @param {string} deviceName The device name * * @param {string} volumeContainerName The volume container name. * * @param {string} volumeName The volume name. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(deviceName: string, volumeContainerName: string, volumeName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * StorageAccountCredentials * __NOTE__: An instance of this class is automatically created for an * instance of the StorSimple8000SeriesManagementClient. */ export interface StorageAccountCredentials { /** * Gets all the storage account credentials in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageAccountCredentialList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagerWithHttpOperationResponse(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageAccountCredentialList>>; /** * Gets all the storage account credentials in a manager. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageAccountCredentialList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {StorageAccountCredentialList} [result] - The deserialized result object if an error did not occur. * See {@link StorageAccountCredentialList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManager(resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageAccountCredentialList>; listByManager(resourceGroupName: string, managerName: string, callback: ServiceCallback<models.StorageAccountCredentialList>): void; listByManager(resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageAccountCredentialList>): void; /** * Gets the properties of the specified storage account credential name. * * @param {string} storageAccountCredentialName The name of storage account * credential to be fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageAccountCredential>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageAccountCredential>>; /** * Gets the properties of the specified storage account credential name. * * @param {string} storageAccountCredentialName The name of storage account * credential to be fetched. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageAccountCredential} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {StorageAccountCredential} [result] - The deserialized result object if an error did not occur. * See {@link StorageAccountCredential} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageAccountCredential>; get(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.StorageAccountCredential>): void; get(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageAccountCredential>): void; /** * Creates or updates the storage account credential. * * @param {string} storageAccountCredentialName The storage account credential * name. * * @param {object} parameters The storage account credential to be added or * updated. * * @param {string} parameters.endPoint The storage endpoint * * @param {string} parameters.sslStatus Signifies whether SSL needs to be * enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {object} [parameters.accessKey] The details of the storage account * password. * * @param {string} parameters.accessKey.value The value of the secret. * * @param {string} [parameters.accessKey.encryptionCertThumbprint] Thumbprint * certificate that was used to encrypt "Value". If the value in unencrypted, * it will be null. * * @param {string} parameters.accessKey.encryptionAlgorithm The algorithm used * to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageAccountCredential>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageAccountCredential>>; /** * Creates or updates the storage account credential. * * @param {string} storageAccountCredentialName The storage account credential * name. * * @param {object} parameters The storage account credential to be added or * updated. * * @param {string} parameters.endPoint The storage endpoint * * @param {string} parameters.sslStatus Signifies whether SSL needs to be * enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {object} [parameters.accessKey] The details of the storage account * password. * * @param {string} parameters.accessKey.value The value of the secret. * * @param {string} [parameters.accessKey.encryptionCertThumbprint] Thumbprint * certificate that was used to encrypt "Value". If the value in unencrypted, * it will be null. * * @param {string} parameters.accessKey.encryptionAlgorithm The algorithm used * to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageAccountCredential} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {StorageAccountCredential} [result] - The deserialized result object if an error did not occur. * See {@link StorageAccountCredential} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageAccountCredential>; createOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.StorageAccountCredential>): void; createOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageAccountCredential>): void; /** * Deletes the storage account credential. * * @param {string} storageAccountCredentialName The name of the storage account * credential. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the storage account credential. * * @param {string} storageAccountCredentialName The name of the storage account * credential. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; deleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates or updates the storage account credential. * * @param {string} storageAccountCredentialName The storage account credential * name. * * @param {object} parameters The storage account credential to be added or * updated. * * @param {string} parameters.endPoint The storage endpoint * * @param {string} parameters.sslStatus Signifies whether SSL needs to be * enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {object} [parameters.accessKey] The details of the storage account * password. * * @param {string} parameters.accessKey.value The value of the secret. * * @param {string} [parameters.accessKey.encryptionCertThumbprint] Thumbprint * certificate that was used to encrypt "Value". If the value in unencrypted, * it will be null. * * @param {string} parameters.accessKey.encryptionAlgorithm The algorithm used * to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<StorageAccountCredential>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateOrUpdateWithHttpOperationResponse(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StorageAccountCredential>>; /** * Creates or updates the storage account credential. * * @param {string} storageAccountCredentialName The storage account credential * name. * * @param {object} parameters The storage account credential to be added or * updated. * * @param {string} parameters.endPoint The storage endpoint * * @param {string} parameters.sslStatus Signifies whether SSL needs to be * enabled or not. Possible values include: 'Enabled', 'Disabled' * * @param {object} [parameters.accessKey] The details of the storage account * password. * * @param {string} parameters.accessKey.value The value of the secret. * * @param {string} [parameters.accessKey.encryptionCertThumbprint] Thumbprint * certificate that was used to encrypt "Value". If the value in unencrypted, * it will be null. * * @param {string} parameters.accessKey.encryptionAlgorithm The algorithm used * to encrypt "Value". Possible values include: 'None', 'AES256', * 'RSAES_PKCS1_v_1_5' * * @param {string} [parameters.kind] The Kind of the object. Currently only * Series8000 is supported. Possible values include: 'Series8000' * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {StorageAccountCredential} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {StorageAccountCredential} [result] - The deserialized result object if an error did not occur. * See {@link StorageAccountCredential} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreateOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StorageAccountCredential>; beginCreateOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, callback: ServiceCallback<models.StorageAccountCredential>): void; beginCreateOrUpdate(storageAccountCredentialName: string, parameters: models.StorageAccountCredential, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StorageAccountCredential>): void; /** * Deletes the storage account credential. * * @param {string} storageAccountCredentialName The name of the storage account * credential. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the storage account credential. * * @param {string} storageAccountCredentialName The name of the storage account * credential. * * @param {string} resourceGroupName The resource group name * * @param {string} managerName The manager name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(storageAccountCredentialName: string, resourceGroupName: string, managerName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; }
the_stack
import * as msRest from "@azure/ms-rest-js"; /** * An interface representing MultiLanguageInput. */ export interface MultiLanguageInput { /** * This is the 2 letter ISO 639-1 representation of a language. For example, use "en" for * English; "es" for Spanish etc., */ language?: string; /** * Unique, non-empty document identifier. */ id?: string; text?: string; } /** * An interface representing MultiLanguageBatchInput. */ export interface MultiLanguageBatchInput { documents?: MultiLanguageInput[]; } /** * An interface representing MatchRecord. */ export interface MatchRecord { /** * (optional) If a well-known item with Wikipedia link is recognized, a decimal number denoting * the confidence level of the Wikipedia info will be returned. */ wikipediaScore?: number; /** * (optional) If an entity type is recognized, a decimal number denoting the confidence level of * the entity type will be returned. */ entityTypeScore?: number; /** * Entity text as appears in the request. */ text?: string; /** * Start position (in Unicode characters) for the entity match text. */ offset?: number; /** * Length (in Unicode characters) for the entity match text. */ length?: number; } /** * An interface representing EntityRecord. */ export interface EntityRecord { /** * Entity formal name. */ name?: string; /** * List of instances this entity appears in the text. */ matches?: MatchRecord[]; /** * Wikipedia language for which the WikipediaId and WikipediaUrl refers to. */ wikipediaLanguage?: string; /** * Wikipedia unique identifier of the recognized entity. */ wikipediaId?: string; /** * URL for the entity's Wikipedia page. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly wikipediaUrl?: string; /** * Bing unique identifier of the recognized entity. Use in conjunction with the Bing Entity * Search API to fetch additional relevant information. */ bingId?: string; /** * Entity type from Named Entity Recognition model */ type?: string; /** * Entity sub type from Named Entity Recognition model */ subType?: string; } /** * An interface representing DocumentStatistics. */ export interface DocumentStatistics { /** * Number of text elements recognized in the document. */ charactersCount?: number; /** * Number of transactions for the document. */ transactionsCount?: number; } /** * An interface representing EntitiesBatchResultItem. */ export interface EntitiesBatchResultItem { /** * Unique, non-empty document identifier. */ id?: string; /** * Recognized entities in the document. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly entities?: EntityRecord[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the document payload. */ statistics?: DocumentStatistics; } /** * An interface representing ErrorRecord. */ export interface ErrorRecord { /** * Input document unique identifier the error refers to. */ id?: string; /** * Error message. */ message?: string; } /** * An interface representing RequestStatistics. */ export interface RequestStatistics { /** * Number of documents submitted in the request. */ documentsCount?: number; /** * Number of valid documents. This excludes empty, over-size limit or non-supported languages * documents. */ validDocumentsCount?: number; /** * Number of invalid documents. This includes empty, over-size limit or non-supported languages * documents. */ erroneousDocumentsCount?: number; /** * Number of transactions for the request. */ transactionsCount?: number; } /** * An interface representing EntitiesBatchResult. */ export interface EntitiesBatchResult { /** * Response by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documents?: EntitiesBatchResultItem[]; /** * Errors and Warnings by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly errors?: ErrorRecord[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the request payload. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statistics?: RequestStatistics; } /** * An interface representing InternalError. */ export interface InternalError { code?: string; message?: string; innerError?: InternalError; } /** * An interface representing ErrorResponse. */ export interface ErrorResponse { code?: string; message?: string; target?: string; innerError?: InternalError; } /** * An interface representing KeyPhraseBatchResultItem. */ export interface KeyPhraseBatchResultItem { /** * Unique, non-empty document identifier. */ id?: string; /** * A list of representative words or phrases. The number of key phrases returned is proportional * to the number of words in the input document. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly keyPhrases?: string[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the document payload. */ statistics?: DocumentStatistics; } /** * An interface representing KeyPhraseBatchResult. */ export interface KeyPhraseBatchResult { /** * Response by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documents?: KeyPhraseBatchResultItem[]; /** * Errors and Warnings by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly errors?: ErrorRecord[]; /** * =(Optional) if showStats=true was specified in the request this field will contain information * about the request payload. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statistics?: RequestStatistics; } /** * An interface representing LanguageInput. */ export interface LanguageInput { countryHint?: string; /** * Unique, non-empty document identifier. */ id?: string; text?: string; } /** * An interface representing LanguageBatchInput. */ export interface LanguageBatchInput { documents?: LanguageInput[]; } /** * An interface representing DetectedLanguage. */ export interface DetectedLanguage { /** * Long name of a detected language (e.g. English, French). */ name?: string; /** * A two letter representation of the detected language according to the ISO 639-1 standard (e.g. * en, fr). */ iso6391Name?: string; /** * A confidence score between 0 and 1. Scores close to 1 indicate 100% certainty that the * identified language is true. */ score?: number; } /** * An interface representing LanguageBatchResultItem. */ export interface LanguageBatchResultItem { /** * Unique, non-empty document identifier. */ id?: string; /** * A list of extracted languages. */ detectedLanguages?: DetectedLanguage[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the document payload. */ statistics?: DocumentStatistics; } /** * An interface representing LanguageBatchResult. */ export interface LanguageBatchResult { /** * Response by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documents?: LanguageBatchResultItem[]; /** * Errors and Warnings by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly errors?: ErrorRecord[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the request payload. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statistics?: RequestStatistics; } /** * An interface representing SentimentBatchResultItem. */ export interface SentimentBatchResultItem { /** * Unique, non-empty document identifier. */ id?: string; /** * A decimal number between 0 and 1 denoting the sentiment of the document. A score above 0.7 * usually refers to a positive document while a score below 0.3 normally has a negative * connotation. Mid values refer to neutral text. */ score?: number; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the document payload. */ statistics?: DocumentStatistics; } /** * An interface representing SentimentBatchResult. */ export interface SentimentBatchResult { /** * Response by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly documents?: SentimentBatchResultItem[]; /** * Errors and Warnings by document * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly errors?: ErrorRecord[]; /** * (Optional) if showStats=true was specified in the request this field will contain information * about the request payload. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statistics?: RequestStatistics; } /** * Optional Parameters. */ export interface TextAnalyticsClientDetectLanguageOptionalParams extends msRest.RequestOptionsBase { /** * (optional) if set to true, response will contain input and document level statistics. */ showStats?: boolean; /** * Collection of documents to analyze. */ languageBatchInput?: LanguageBatchInput; } /** * Optional Parameters. */ export interface TextAnalyticsClientEntitiesOptionalParams extends msRest.RequestOptionsBase { /** * (optional) if set to true, response will contain input and document level statistics. */ showStats?: boolean; /** * Collection of documents to analyze. */ multiLanguageBatchInput?: MultiLanguageBatchInput; } /** * Optional Parameters. */ export interface TextAnalyticsClientKeyPhrasesOptionalParams extends msRest.RequestOptionsBase { /** * (optional) if set to true, response will contain input and document level statistics. */ showStats?: boolean; /** * Collection of documents to analyze. Documents can now contain a language field to indicate the * text language */ multiLanguageBatchInput?: MultiLanguageBatchInput; } /** * Optional Parameters. */ export interface TextAnalyticsClientSentimentOptionalParams extends msRest.RequestOptionsBase { /** * (optional) if set to true, response will contain input and document level statistics. */ showStats?: boolean; /** * Collection of documents to analyze. */ multiLanguageBatchInput?: MultiLanguageBatchInput; } /** * Contains response data for the detectLanguage operation. */ export type DetectLanguageResponse = LanguageBatchResult & { /** * 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: LanguageBatchResult; }; }; /** * Contains response data for the entities operation. */ export type EntitiesResponse = EntitiesBatchResult & { /** * 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: EntitiesBatchResult; }; }; /** * Contains response data for the keyPhrases operation. */ export type KeyPhrasesResponse = KeyPhraseBatchResult & { /** * 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: KeyPhraseBatchResult; }; }; /** * Contains response data for the sentiment operation. */ export type SentimentResponse = { /** * The parsed response body. */ body: any; /** * 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: any; }; };
the_stack
import { ClassType, collectForMicrotask, getClassName, isPrototypeOfBase, toFastProperties } from '@deepkit/core'; import { isBehaviorSubject, isSubject } from '@deepkit/core-rxjs'; import { assertType, findMember, getValidatorFunction, Guard, parametersToTuple, ReflectionClass, ReflectionKind, serializeType, Type, TypeObjectLiteral, typeOf, TypeTuple, ValidationError, ValidationErrorItem } from '@deepkit/type'; import { isObservable, Observable, Subject, Subscription } from 'rxjs'; import { Collection, CollectionEvent, CollectionQueryModel, CollectionQueryModelInterface, CollectionState } from '../collection'; import { getActions } from '../decorators'; import { ActionMode, ActionObservableTypes, EntitySubject, isEntitySubject, rpcActionObservableSubscribeId, rpcActionType, rpcResponseActionCollectionRemove, rpcResponseActionCollectionSort, rpcResponseActionObservable, rpcResponseActionObservableSubscriptionError, rpcResponseActionType, RpcTypes, } from '../model'; import { rpcEncodeError, RpcMessage } from '../protocol'; import { RpcMessageBuilder } from './kernel'; import { RpcControllerAccess, RpcKernelSecurity, SessionState } from './security'; import { InjectorContext, InjectorModule } from '@deepkit/injector'; export type ActionTypes = { actionCallSchema: TypeObjectLiteral, //with args as property parametersValidate: Guard<any>, parameters: TypeTuple, mode: ActionMode; type: Type; //the type T of Collection<T>, EntitySubject<T>, Observable<T>, or return type of the function if mode=arbitrary resultSchema: TypeObjectLiteral, //with v as property observableNextSchema?: TypeObjectLiteral, //with v as property collectionSchema?: Type, //with v as array property collectionQueryModel?: Type, }; function getV(container: TypeObjectLiteral): Type { const found = findMember('v', container); if (!found) throw new Error('v not found'); assertType(found, ReflectionKind.propertySignature); return found.type; } export class RpcServerAction { protected cachedActionsTypes: { [id: string]: ActionTypes } = {}; protected observableSubjects: { [id: number]: { subject: Subject<any>, completedByClient: boolean, subscription: Subscription } } = {}; protected collections: { [id: number]: { collection: Collection<any>, unsubscribe: () => void } } = {}; protected observables: { [id: number]: { observable: Observable<any>, classType: ClassType, method: string, types: ActionTypes, subscriptions: { [id: number]: { sub?: Subscription, active: boolean, complete: () => void } }, } } = {}; constructor( protected controllers: Map<string, { controller: ClassType, module?: InjectorModule }>, protected injector: InjectorContext, protected security: RpcKernelSecurity, protected sessionState: SessionState, ) { } public async handleActionTypes(message: RpcMessage, response: RpcMessageBuilder) { const body = message.parseBody<rpcActionType>(); const types = await this.loadTypes(body.controller, body.method); response.reply<rpcResponseActionType>(RpcTypes.ResponseActionType, { mode: types.mode, type: serializeType(types.type), parameters: serializeType(types.parameters), }); } public async onClose() { for (const collection of Object.values(this.collections)) { if (!collection.collection.closed) { collection.unsubscribe(); collection.collection.unsubscribe(); } } for (const observable of Object.values(this.observables)) { for (const sub of Object.values(observable.subscriptions)) { if (sub.sub && !sub.sub.closed) sub.sub.unsubscribe(); } } for (const subject of Object.values(this.observableSubjects)) { if (!subject.subject.closed) subject.subject.complete(); } } protected async hasControllerAccess(controllerAccess: RpcControllerAccess): Promise<boolean> { return await this.security.hasControllerAccess(this.sessionState.getSession(), controllerAccess); } protected async loadTypes(controller: string, methodName: string): Promise<ActionTypes> { const cacheId = controller + '!' + methodName; let types = this.cachedActionsTypes[cacheId]; if (types) return types; const classType = this.controllers.get(controller); if (!classType) { throw new Error(`No controller registered for id ${controller}`); } const action = getActions(classType.controller).get(methodName); if (!action) { throw new Error(`Action unknown ${methodName}`); } const controllerAccess: RpcControllerAccess = { controllerName: controller, actionName: methodName, controllerClassType: classType.controller, actionGroups: action.groups, actionData: action.data }; if (!await this.hasControllerAccess(controllerAccess)) { throw new Error(`Access denied to action ${methodName}`); } const methodReflection = ReflectionClass.from(classType.controller).getMethod(methodName); const method = methodReflection.type; assertType(method, ReflectionKind.method); let mode: ActionMode = 'arbitrary'; const parameters: TypeTuple = parametersToTuple(methodReflection.getParameters().map(v => v.parameter)); const actionCallSchema: TypeObjectLiteral = { kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'args', parent: Object as any, type: parameters, } ] }; let nextSchema: Type | undefined = undefined; let unwrappedReturnType = methodReflection.getReturnType(); if (unwrappedReturnType.kind === ReflectionKind.promise) { unwrappedReturnType = unwrappedReturnType.type; } let type: Type = unwrappedReturnType; let collectionSchema: Type | undefined; let collectionQueryModel: Type | undefined; if (unwrappedReturnType.kind === ReflectionKind.class) { if (isPrototypeOfBase(unwrappedReturnType.classType, Collection)) { mode = 'collection'; type = unwrappedReturnType.typeArguments ? unwrappedReturnType.typeArguments[0] : { kind: ReflectionKind.any }; collectionSchema = { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', parent: Object as any, optional: true, type: { kind: ReflectionKind.array, type: type } }] }; collectionQueryModel = typeOf<CollectionQueryModelInterface<unknown>>([type]) as TypeObjectLiteral; } else if (isPrototypeOfBase(unwrappedReturnType.classType, EntitySubject)) { mode = 'entitySubject'; type = unwrappedReturnType.typeArguments ? unwrappedReturnType.typeArguments[0] : { kind: ReflectionKind.any }; } else if (isPrototypeOfBase(unwrappedReturnType.classType, Observable)) { mode = 'observable'; type = unwrappedReturnType.typeArguments ? unwrappedReturnType.typeArguments[0] : { kind: ReflectionKind.any }; nextSchema = { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'id', parent: Object as any, type: { kind: ReflectionKind.number }, }, { kind: ReflectionKind.propertySignature, name: 'v', parent: Object as any, optional: true, type: type, }] }; } } const resultSchema: TypeObjectLiteral = { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', parent: Object as any, optional: true, type: type, }] }; types = this.cachedActionsTypes[cacheId] = { parameters, actionCallSchema, resultSchema, mode, type, parametersValidate: getValidatorFunction(undefined, parameters), observableNextSchema: nextSchema, collectionSchema, collectionQueryModel, }; toFastProperties(this.cachedActionsTypes); return types; } public async handle(message: RpcMessage, response: RpcMessageBuilder) { switch (message.type) { case RpcTypes.ActionObservableSubscribe: { const observable = this.observables[message.id]; if (!observable) return response.error(new Error('No observable found')); const { types, classType, method } = observable; const body = message.parseBody<rpcActionObservableSubscribeId>(); if (observable.subscriptions[body.id]) return response.error(new Error('Subscription already created')); if (!types.observableNextSchema) return response.error(new Error('No observable type detected')); const sub: { active: boolean, sub?: Subscription, complete: () => void } = { active: true, complete: () => { sub.active = false; if (sub.sub) sub.sub.unsubscribe(); response.reply<rpcActionObservableSubscribeId>(RpcTypes.ResponseActionObservableComplete, { id: body.id }); } }; observable.subscriptions[body.id] = sub; sub.sub = observable.observable.subscribe((next) => { if (!sub.active) return; response.reply(RpcTypes.ResponseActionObservableNext, { id: body.id, v: next }, types.observableNextSchema); }, (error) => { const extracted = rpcEncodeError(this.security.transformError(error)); response.reply<rpcResponseActionObservableSubscriptionError>(RpcTypes.ResponseActionObservableError, { ...extracted, id: body.id }); }, () => { response.reply<rpcActionObservableSubscribeId>(RpcTypes.ResponseActionObservableComplete, { id: body.id }); }); break; } case RpcTypes.ActionCollectionUnsubscribe: { const collection = this.collections[message.id]; if (!collection) return response.error(new Error('No collection found')); collection.unsubscribe(); delete this.collections[message.id]; break; } case RpcTypes.ActionCollectionModel: { const collection = this.collections[message.id]; if (!collection) return response.error(new Error('No collection found')); const body = message.parseBody<CollectionQueryModel<any>>(); //todo, add correct type argument collection.collection.model.set(body); collection.collection.model.changed(); break; } case RpcTypes.ActionObservableUnsubscribe: { const observable = this.observables[message.id]; if (!observable) return response.error(new Error('No observable to unsubscribe found')); const body = message.parseBody<rpcActionObservableSubscribeId>(); const sub = observable.subscriptions[body.id]; if (!sub) return response.error(new Error('No subscription found')); sub.active = false; if (sub.sub) { sub.sub.unsubscribe(); } delete observable.subscriptions[body.id]; break; } case RpcTypes.ActionObservableDisconnect: { const observable = this.observables[message.id]; if (!observable) return response.error(new Error('No observable to disconnect found')); for (const sub of Object.values(observable.subscriptions)) { sub.complete(); //we send all active subscriptions it was completed } delete this.observables[message.id]; break; } case RpcTypes.ActionObservableSubjectUnsubscribe: { //aka completed const subject = this.observableSubjects[message.id]; if (!subject) return response.error(new Error('No subject to unsubscribe found')); subject.completedByClient = true; subject.subject.complete(); delete this.observableSubjects[message.id]; break; } } } public async handleAction(message: RpcMessage, response: RpcMessageBuilder) { const body = message.parseBody<rpcActionType>(); const controller = this.controllers.get(body.controller); if (!controller) throw new Error(`No controller registered for id ${body.controller}`); const types = await this.loadTypes(body.controller, body.method); let value: { args: any[] } = { args: [] }; try { value = message.parseBody(types.actionCallSchema); } catch (error: any) { if (error instanceof ValidationError) { //remove `.args` from path error = ValidationError.from(error.errors.map(v => ({ ...v, path: v.path.replace('args.', '') }))); } return response.error(error); } const controllerClassType = this.injector.get(controller.controller, controller.module); if (!controllerClassType) { response.error(new Error(`No instance of ${getClassName(controller.controller)} found.`)); } // const converted = types.parametersDeserialize(value.args); const errors: ValidationErrorItem[] = []; types.parametersValidate(value.args, { errors }); if (errors.length) { return response.error(new ValidationError(errors)); } try { const result = await controllerClassType[body.method](...value.args); if (isEntitySubject(result)) { response.reply(RpcTypes.ResponseEntity, { v: result.value }, types.resultSchema); } else if (result instanceof Collection) { const collection = result; if (!types.collectionSchema) throw new Error('No collectionSchema set'); if (!types.collectionQueryModel) throw new Error('No collectionQueryModel set'); response.composite(RpcTypes.ResponseActionCollection) .add(RpcTypes.ResponseActionCollectionModel, collection.model, types.collectionQueryModel) .add<CollectionState>(RpcTypes.ResponseActionCollectionState, collection.state) .add(RpcTypes.ResponseActionCollectionSet, { v: collection.all() }, types.collectionSchema) .send(); let unsubscribed = false; //we queue many events up for the next microtask using collectForMicrotask, and then send //everything as one composite message. const eventsSub = collection.event.subscribe(collectForMicrotask((events: CollectionEvent<any>[]) => { if (unsubscribed) return; const composite = response.composite(RpcTypes.ResponseActionCollectionChange); for (const event of events) { if (event.type === 'add') { //when the user has already a EntitySubject on one of those event.items, //then we technically send it unnecessarily. However, we would have to introduce //a new RpcType to send only the IDs, which is not yet implemented. composite.add(RpcTypes.ResponseActionCollectionAdd, { v: event.items }, types.collectionSchema); } else if (event.type === 'remove') { composite.add<rpcResponseActionCollectionRemove>(RpcTypes.ResponseActionCollectionRemove, { ids: event.ids, }); } else if (event.type === 'update') { composite.add(RpcTypes.ResponseActionCollectionUpdate, { v: event.items }, types.collectionSchema); } else if (event.type === 'set') { composite.add(RpcTypes.ResponseActionCollectionSet, { v: collection.all() }, types.collectionSchema); } else if (event.type === 'state') { composite.add<CollectionState>(RpcTypes.ResponseActionCollectionState, collection.state); } else if (event.type === 'sort') { composite.add<rpcResponseActionCollectionSort>(RpcTypes.ResponseActionCollectionSort, { ids: event.ids, }); } } composite.send(); })); collection.addTeardown(() => { const c = this.collections[message.id]; if (c) c.unsubscribe(); }); this.collections[message.id] = { collection, unsubscribe: () => { if (unsubscribed) return; unsubscribed = true; eventsSub.unsubscribe(); collection.unsubscribe(); } }; } else if (isObservable(result)) { this.observables[message.id] = { observable: result, subscriptions: {}, types, classType: controller.controller, method: body.method }; let type: ActionObservableTypes = ActionObservableTypes.observable; if (isSubject(result)) { type = ActionObservableTypes.subject; this.observableSubjects[message.id] = { subject: result, completedByClient: false, subscription: result.subscribe((next) => { response.reply(RpcTypes.ResponseActionObservableNext, { id: message.id, v: next }, types.observableNextSchema); }, (error) => { const extracted = rpcEncodeError(this.security.transformError(error)); response.reply<rpcResponseActionObservableSubscriptionError>(RpcTypes.ResponseActionObservableError, { ...extracted, id: message.id }); }, () => { const v = this.observableSubjects[message.id]; if (v && v.completedByClient) return; //we don't send ResponseActionObservableComplete when the client issued unsubscribe response.reply<rpcActionObservableSubscribeId>(RpcTypes.ResponseActionObservableComplete, { id: message.id }); }) }; if (isBehaviorSubject(result)) { type = ActionObservableTypes.behaviorSubject; } } response.reply<rpcResponseActionObservable>(RpcTypes.ResponseActionObservable, { type }); } else { response.reply(RpcTypes.ResponseActionSimple, { v: result }, types.resultSchema); } } catch (error: any) { response.error(this.security.transformError(error)); } } }
the_stack
import type { Rule } from "eslint"; import type { RegExpLiteral, SourceLocation } from "estree"; import { RegExpParser, visitRegExpAST } from "regexpp"; import { Alternative, CharacterClassElement, Element, Flags, Pattern, Quantifier } from "regexpp/ast"; import { RegExpVisitor } from "regexpp/visitor"; export type CleanRegexRule = Rule.RuleModule & { meta: Rule.RuleMetaData & { type: "problem" | "suggestion" | "layout"; docs: { description: string; url: string; }; }; }; export type PatternElement = Pattern | Element | CharacterClassElement | Alternative; export interface RegexFixOptions { /** * The fix depends on these nodes. This means that the fix may not change these nodes but the rule creating the fix * assumes that they are not changed by another fix. */ dependsOn?: PatternElement | readonly PatternElement[]; /** * Similar to `dependsOn`, this means that the fix depends on at least one flags. This means that flags may not be * changed by other fixes. */ dependsOnFlags?: boolean; } export interface RegexRuleListenerContext { readonly pattern: Pattern; readonly flags: Flags; readonly visitAST: (handlers: RegExpVisitor.Handlers) => void; readonly reportElement: (element: PatternElement) => ReportProps; readonly reportQuantifier: (element: Quantifier) => ReportProps; readonly reportFlags: () => ReportProps; readonly reportElements: (elements: readonly PatternElement[]) => ReportProps; readonly replaceLiteral: (patternReplacement: string, flagsReplacement: string) => ReplaceProps; readonly replaceElement: (element: PatternElement, replacement: string, options?: RegexFixOptions) => ReplaceProps; readonly replaceQuantifier: (element: Quantifier, replacement: string, options?: RegexFixOptions) => ReplaceProps; readonly replaceFlags: (replacement: string, options?: RegexFixOptions) => ReplaceProps; readonly removeElement: (element: PatternElement, options?: RegexFixOptions) => ReplaceProps; readonly parseExpression: (expression: string) => Pattern | null; } export interface ReportProps { loc: SourceLocation; } export interface ReplaceProps extends ReportProps { fix: (fixer: Rule.RuleFixer) => Rule.Fix; } const parser = new RegExpParser(); const patternCache = new Map<string, Pattern | null>(); const flagsCache = new Map<string, Flags | null>(); function getPattern(source: string, uFlag: boolean): Pattern | null { const key = `${uFlag ? "u" : ""}:${source}`; let pattern = patternCache.get(key); if (pattern === undefined) { pattern = null; try { pattern = parser.parsePattern(source, undefined, undefined, uFlag); } catch (error) { /* no-op */ } patternCache.set(key, pattern); } return pattern; } function getFlags(flags: string): Flags | null { const key = flags; let f = flagsCache.get(key); if (f === undefined) { f = null; try { f = parser.parseFlags(flags); } catch (error) { /* no-op */ } flagsCache.set(key, f); } return f; } function createListenerContext(regexNode: RegExpLiteral): RegexRuleListenerContext | null { const pattern = getPattern(regexNode.regex.pattern, regexNode.regex.flags.indexOf("u") != -1); const flags = getFlags(regexNode.regex.flags); // both have to be valid if (!pattern || !flags) { return null; } function replaceLiteralImpl(patternReplacement: string, flagsReplacement: string): ReplaceProps { const range = regexNode.range; if (!range) { throw new Error("The regex literal node does not have a range associated with it."); } return { loc: copyLoc(regexNode.loc), fix: fixer => fixer.replaceTextRange(range, `/${patternReplacement}/${flagsReplacement}`), }; } function replaceElementImpl( element: ElementLocation, replacement: string, options?: RegexFixOptions ): ReplaceProps { if (options?.dependsOnFlags) { // replace the whole literal const pattern = regexNode.regex.pattern; const flags = regexNode.regex.flags; const patternReplacement = pattern.substring(0, element.start) + replacement + pattern.substring(element.end); return { loc: locOfElement(regexNode, element), fix: replaceLiteralImpl(patternReplacement, flags).fix, }; } else { const region: ElementLocation = elementLocUnion([...toArray(options?.dependsOn), element]) ?? element; if (region.start === element.start && region.end === element.end) { // the element doesn't depend on anything return { loc: locOfElement(regexNode, element), fix: fixer => replaceElement(fixer, regexNode, element, replacement), }; } else { // the elements also depends on some other elements const regionPattern = regexNode.regex.pattern.substring(region.start, region.end); const regionReplacement = regionPattern.substring(0, element.start - region.start) + replacement + regionPattern.substring(element.end - region.start); return { loc: locOfElement(regexNode, element), fix: fixer => replaceElement(fixer, regexNode, region, regionReplacement), }; } } } const listenerContext: RegexRuleListenerContext = { pattern, flags, visitAST(handlers) { visitRegExpAST(pattern, handlers); }, reportElement(element) { return { loc: locOfElement(regexNode, element) }; }, reportQuantifier(element) { return { loc: locOfElement(regexNode, elementLocOfQuantifier(element)) }; }, reportFlags() { return { loc: locOfRegexFlags(regexNode) }; }, reportElements(elements) { const union = elementLocUnion(elements); if (!union) { throw new Error("There has to be at least one element to report!"); } return { loc: locOfElement(regexNode, union) }; }, replaceLiteral: replaceLiteralImpl, replaceElement: replaceElementImpl, replaceQuantifier(element, replacement, options) { const quant = elementLocOfQuantifier(element); return replaceElementImpl(quant, replacement, options); }, replaceFlags(replacement, options) { if (options?.dependsOn) { // we depend on some elements, so let's just replace the whole literal return { loc: locOfRegexFlags(regexNode), fix: fixer => replaceFlags(fixer, regexNode, replacement), }; } else { return { loc: locOfRegexFlags(regexNode), fix: replaceLiteralImpl(regexNode.regex.pattern, replacement).fix, }; } }, removeElement(element, options) { const parent = element.parent; if (parent && parent.type === "Alternative" && parent.elements.length === 1) { // this element is the only element const pattern = parent.parent; if (pattern.type === "Pattern" && pattern.alternatives.length === 1) { // the whole pattern only has one alternative // if this element was removed, the pattern's source would be an empty string which // is invalid (//), so replace it with an empty non-capturing group instead. return replaceElementImpl(element, "(?:)", options); } } if (parent && parent.type === "Quantifier") { // if this element was removed, the quantifier will quantify the preceding element. return replaceElementImpl(element, "(?:)", options); } return replaceElementImpl(element, "", options); }, parseExpression(expression) { return getPattern(expression, regexNode.regex.flags.indexOf("u") != -1); }, }; return listenerContext; } export function createRuleListener(listener: (context: RegexRuleListenerContext) => void): Rule.RuleListener { return { Literal(node) { const regexNode = node as RegExpLiteral; if (typeof regexNode.regex === "object") { const listenerContext = createListenerContext(regexNode); if (listenerContext !== null) { listener.call(this, listenerContext); } } }, }; } /** * The location of a RegExpp element (all nodes except the flags). */ interface ElementLocation { start: number; end: number; } function elementLocUnion(array: readonly Readonly<ElementLocation>[]): ElementLocation | undefined { if (array.length === 0) { return undefined; } else { let start = array[0].start; let end = array[0].end; for (const item of array) { start = Math.min(start, item.start); end = Math.max(end, item.end); } return { start, end }; } } function elementLocOfQuantifier(element: Readonly<Quantifier>): ElementLocation { return { start: element.element.end, end: element.end }; } function copyLoc(loc: SourceLocation | undefined | null): SourceLocation { if (!loc) { throw new Error("The node does not include source location information!"); } return { start: { ...loc.start }, end: { ...loc.end }, }; } function locOfElement(node: RegExpLiteral, element: Readonly<ElementLocation>): SourceLocation { const loc = copyLoc(node.loc); const offset = loc.start.column + "/".length; loc.start.column = offset + element.start; loc.end.column = offset + element.end; return loc; } function locOfRegexFlags(node: RegExpLiteral): SourceLocation { const loc = copyLoc(node.loc); const flagCount = Math.max(1, node.regex.flags.length); loc.start.column = loc.end.column - flagCount; return loc; } function replaceElement( fixer: Rule.RuleFixer, node: RegExpLiteral, element: Readonly<ElementLocation>, replacement: string ): Rule.Fix { if (!node.range) { throw new Error("The given node does not have range information."); } const offset = node.range[0] + "/".length; return fixer.replaceTextRange([offset + element.start, offset + element.end], replacement); } /** * Replaces the flags of the given regex literal with the given string. */ function replaceFlags(fixer: Rule.RuleFixer, node: RegExpLiteral, replacement: string): Rule.Fix { if (!node.range) { throw new Error("The given node does not have range information."); } const start = node.range[1] - node.regex.flags.length; return fixer.replaceTextRange([start, node.range[1]], replacement); } function toArray<T>(value: T | readonly T[] | undefined): readonly T[] { if (Array.isArray(value)) { return value; } else if (value === undefined) { return []; } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any return [value as any]; } } export const repoTreeRoot = "https://github.com/RunDevelopment/eslint-plugin-clean-regex/blob/master"; /** * Returns the rule name of the rule behind the given filename of a rule. * * @param filename The filename of path of a rule. */ export function filenameToRule(filename: string): string { const rule = (/([-\w]+)\.[jt]s$/.exec(filename) || [undefined, undefined])[1]; if (!rule) { throw new Error(`Invalid rule filename: ${filename}`); } return rule; } /** * Returns the URL of the doc of the given rule. */ export function getDocUrl(rule: string): string { return `${repoTreeRoot}/docs/rules/${rule}.md`; }
the_stack
import react = require('react'); import style = require('ts-style'); import underscore = require('underscore'); import urijs = require('urijs'); import { div, img } from './base/dom_factory'; import err_util = require('../lib/base/err_util'); import event_stream = require('../lib/base/event_stream'); import image = require('../lib/siteinfo/image'); import key_value_store = require('../lib/base/key_value_store'); import site_info = require('../lib/siteinfo/site_info'); import url_util = require('../lib/base/url_util'); var theme = style.create( { action: { cursor: 'pointer', }, container: { width: 48, height: 48, backgroundColor: 'white', border: '1px solid #bbb', // make icon circular borderRadius: '50%', overflow: 'hidden', focused: { boxShadow: '0px 0px 2px 2px rgba(0,0,0,0.2)', }, flexShrink: 0, // fix an issue in WebKit / Blink (tested in iOS 8, // Chrome 39 on Linux) where the border-radius clipping // would not be applied to the child <img> for the icon // when a transition was being applied to a nearby element. // // Forcing the icon container and its descendants into their // own compositing layer resolves the issue // // Possibly related to https://code.google.com/p/chromium/issues/detail?id=430184 transform: 'translate3d(0,0,0)', }, icon: { // horizontally center icon in outline. // Limit to max size of 48x48 but prefer // intrinsic size maxWidth: 48, maxHeight: 48, marginLeft: 'auto', marginRight: 'auto', // vertically center icon in outline display: 'block', position: 'relative', top: '50%', transform: 'translateY(-50%)', // for images that are smaller than the 48px max width, // make the image circular, so that the image and the // container have the same shape. // // If the image already fills the container then // the container's border-radius will make it circular. rounded: { borderRadius: '50%', }, }, }, __filename ); /** Fetch state for an icon returned by IconProvider query. */ export enum IconFetchState { Fetching, ///< Icons associated with the URL are currently being fetched NoIcon, ///< The fetch completed but no matching icon was found Found, ///< The fetch completed and found an icon } export interface Icon { iconUrl: string; state: IconFetchState; width: number; height: number; } /** Provides icon URLs for websites. IconProvider handles fetching * and caching of icons to represent items. * * Call query(url) to lookup the icon associated with a given URL. * If a cached icon is available, it will be returned, otherwise a lookup * will be triggered. * * When the icon associated with a previously looked up URL changes, * the updated event stream will emit the normalized URL. */ export interface IconProvider { /** Stream of icon update events. * Emits the normalized URL (using url_util.normalize) of the location * when the icon for that location is updated. */ updated: event_stream.EventStream<string>; /** Fetch the icon for a given URL. */ query(url: string): Icon; /** Returns true if a given @p updateUrl from IconProvider.updated * matches an item with location @p location. * * The update URL may not match the original item location due to * normalization or if a fallback URL has been used to find * an icon for the item. */ updateMatches(updateUrl: string, itemUrl: string): boolean; } /** Interface for an image loader function * which loads data from an image and returns * a URL that can later be used with an <img> * element to display the image. */ export interface ImageLoader { (data: Uint8Array): string; } // default image loader implementation which uses // URL.createObjectURL() to load an image's data function domImageLoader(data: Uint8Array) { var iconInfo = image.getInfo(data); var mimeType = iconInfo ? image.mimeType(iconInfo.type) : 'application/octet-stream'; let blob = new Blob([data], { type: mimeType }); return URL.createObjectURL(blob); } /** An IconProvider implementation which fetches icons * from a SiteInfoProvider and caches the results * in a local store (eg. an IndexedDB store) for * future use. */ export class BasicIconProvider implements IconProvider { // cache of item URL -> item icon metadata private tempCache: Map<string, Icon>; // persistent cache of item URL -> item icon // image data private diskCache: Cache; private provider: site_info.SiteInfoProvider; private iconSize: number; private loadImage: ImageLoader; public static LOADING_ICON = 'dist/icons/loading.png'; private static DEFAULT_ICON = 'dist/icons/default.png'; updated: event_stream.EventStream<string>; /** Create an icon provider which uses @p provider to fetch * icon data. @p iconSize specifies the size of icon to make from * the available icons for a given URL. * * @param cacheStore A key/value store to use for persisting fetched icons * @param provider A provider to query for icons for a given domain * @param iconSize The preferred size for icons generated by the provider. * Depending on the images that can be retrieved for a URL, * the actual icon image may be larger or smaller than the preferred * size. */ constructor( cacheStore: key_value_store.ObjectStore, provider: site_info.SiteInfoProvider, iconSize: number, imageLoader?: ImageLoader ) { this.tempCache = new Map<string, Icon>(); this.diskCache = new Cache(cacheStore); this.provider = provider; this.iconSize = iconSize; this.updated = new event_stream.EventStream<string>(); this.loadImage = imageLoader; if (!this.loadImage) { this.loadImage = domImageLoader; } // increase the number of max listeners since we will have // one listener for each visible icon this.updated.maxListeners = 100; this.provider.updated.listen(url => { this.queryProviderForIcon( url, false /* query only, do not start a lookup */ ); }); } updateMatches(updateUrl: string, itemUrl: string) { itemUrl = url_util.normalize(itemUrl); return ( updateUrl == itemUrl || updateUrl == this.fallbackUrlForIcon(itemUrl) ); } query(url: string): Icon { url = url_util.normalize(url); if (url.length == 0) { return { iconUrl: BasicIconProvider.DEFAULT_ICON, state: IconFetchState.NoIcon, width: 48, height: 48, }; } if (this.tempCache.get(url)) { var cachedIcon = this.tempCache.get(url); if (cachedIcon.state == IconFetchState.NoIcon) { var fallbackUrl = this.fallbackUrlForIcon(url); if (this.tempCache.get(fallbackUrl)) { return this.tempCache.get(fallbackUrl); } } return cachedIcon; } else { var icon: Icon = { iconUrl: BasicIconProvider.LOADING_ICON, state: IconFetchState.Fetching, width: 48, height: 48, }; this.tempCache.set(url, icon); this.diskCache .query(url) .then(entry => { if (entry) { this.updateCacheEntry(url, entry.icons); } else { this.queryProviderForIcon(url); } }) .catch(err => { this.queryProviderForIcon(url); }); return icon; } } // query icon provider for icon data for a URL and // update the local caches if a result is available. // // 'lookup' specifies whether the icon provider should // perform a (usually remote) lookup or just return // the status of any lookups which have already been // triggered private queryProviderForIcon(url: string, lookup = true) { let lookupResult: site_info.QueryResult; if (lookup) { lookupResult = this.provider.lookup(url); } else { lookupResult = this.provider.status(url); } if (lookupResult.info.icons.length > 0) { // cache icons for future use this.diskCache .insert(url, { icons: lookupResult.info.icons, }) .catch(err => { console.warn( 'Caching icons for URL', url, 'failed', err.message ); }); } if (lookupResult.state === site_info.QueryState.Ready) { this.updateCacheEntry(url, lookupResult.info.icons); } // free icon data this.provider.forget(url); } private updateCacheEntry(url: string, icons: site_info.Icon[]) { var icon = this.tempCache.get(url); var selectedIcon = this.makeIconUrl(icons, this.iconSize); icon.iconUrl = selectedIcon.url; if (icon.iconUrl != '') { icon.state = IconFetchState.Found; icon.width = selectedIcon.icon.width; icon.height = selectedIcon.icon.height; } else { icon.state = IconFetchState.NoIcon; icon.iconUrl = BasicIconProvider.DEFAULT_ICON; icon.width = 48; icon.height = 48; } this.updated.publish(url); if (icons.length == 0) { // if a query against the actual location returns no suitable icons, // try a query against the main domain var fallbackUrl = this.fallbackUrlForIcon(url); if (fallbackUrl && fallbackUrl != url) { this.query(this.fallbackUrlForIcon(url)); } } } // Take a set of icons for a site, pick the best one for a given target // image width of @p minSize and return a blob URL for the image // data private makeIconUrl(icons: site_info.Icon[], minSize: number) { if (icons.length == 0) { return { url: '', icon: null }; } var iconsBySize = underscore.sortBy(icons, icon => { return icon.width; }); // try to find a square icon of the required-size var squareIcon: site_info.Icon; var nonSquareIcon: site_info.Icon; for (var i = 0; i < iconsBySize.length; i++) { var candidate = iconsBySize[i]; if (candidate.width >= minSize) { if (candidate.width == candidate.height) { squareIcon = squareIcon || candidate; } else { nonSquareIcon = nonSquareIcon || candidate; } } } var icon = squareIcon || nonSquareIcon; if (!icon) { icon = iconsBySize[iconsBySize.length - 1]; } return { url: this.loadImage(icon.data), icon: icon }; } // Returns a fallback URL to try if querying an item's URL does // not return an icon. // // (eg. 'https://sub.domain.com/foo/bar' => 'https://www.domain.com') // // We use HTTPS here although there are many sites which do have secure // login pages but whoose main site is not reachable over HTTPS // due to an invalid certificate or simply lack of SSL support. // // We could try an HTTP-only variant of the lookup but this is open // to MITM spoofing if run from the user's system. // private fallbackUrlForIcon(url: string) { url = url_util.normalize(url); var parsedUrl = urijs(url); return 'https://www.' + parsedUrl.domain(); } } interface CacheEntry { icons: site_info.Icon[]; } class Cache { constructor(private store: key_value_store.ObjectStore) {} /** Look up the icons for @p url in the cache. * Resolves with the cache entry if found or undefined * if no such entry exists. */ query(url: string): Promise<CacheEntry> { return this.withKey(url, key => { return this.store.get<CacheEntry>(key); }); } insert(url: string, icons: CacheEntry): Promise<void> { return this.withKey(url, key => { return this.store.set(key, icons); }); } clear(url: string): Promise<void> { return this.withKey(url, key => { return this.store.remove(key); }); } private withKey<T>( url: string, f: (key: string) => Promise<T> ): Promise<T> { var key = urijs(url_util.normalize(url)).hostname(); if (!key) { return Promise.reject<T>(new err_util.BaseError('Invalid URL')); } return f(key); } } export interface IconControlProps extends react.Props<void> { location: string; iconProvider: IconProvider; isFocused: boolean; onClick?: () => void; title?: string; } export class IconControl extends react.Component<IconControlProps, {}> { private iconUpdateListener: (url: string) => void; private setupIconUpdateListener(iconProvider: IconProvider) { if (!this.iconUpdateListener) { this.iconUpdateListener = url => { if ( this.props.location && this.props.iconProvider.updateMatches( url, this.props.location ) ) { this.forceUpdate(); } }; } if (this.props.iconProvider) { this.props.iconProvider.updated.ignore(this.iconUpdateListener); } iconProvider.updated.listen(this.iconUpdateListener); } componentDidMount() { if (!this.iconUpdateListener) { this.setupIconUpdateListener(this.props.iconProvider); } } componentWillUnmount() { if (this.iconUpdateListener && this.props.iconProvider) { this.props.iconProvider.updated.ignore(this.iconUpdateListener); } this.iconUpdateListener = null; } componentWillReceiveProps(nextProps: IconControlProps) { this.setupIconUpdateListener(nextProps.iconProvider); } render() { var icon = this.props.iconProvider.query(this.props.location); var imgStyles: any[] = [theme.icon]; if (icon.width < 48) { // make image rounded if it doesn't fill the container. // For images that do fill the container, we get smoother // anti-aliased rounding for the icon if we only // apply border-radius to the container and not to both // the container and the icon imgStyles.push(theme.icon.rounded); } var containerStyles: any[] = [theme.container]; if (this.props.isFocused) { containerStyles.push(theme.container.focused); } if (this.props.onClick) { containerStyles.push(theme.action); } return div( style.mixin(containerStyles, { onClick: this.props.onClick, title: this.props.title, }), img(style.mixin(imgStyles, { ref: 'img', src: icon.iconUrl })) ); } } type URLString = string; export class FakeIconProvider implements IconProvider { private icons: Map<URLString, Icon>; updated: event_stream.EventStream<string>; constructor() { this.updated = new event_stream.EventStream<string>(); this.icons = new Map<URLString, Icon>(); } query(url: URLString): Icon { var icon = this.icons.get(url); if (icon) { return icon; } else { return { iconUrl: '', state: IconFetchState.NoIcon, width: 48, height: 48, }; } } addIcon(url: URLString, icon: Icon) { this.icons.set(url, icon); this.updated.publish(url); } updateMatches(updateUrl: string, itemUrl: string) { return updateUrl == itemUrl; } } export var IconControlF = react.createFactory(IconControl);
the_stack
import QlogConnection from '@/data/Connection'; import * as qlog from '@/data/QlogSchema'; import * as d3 from 'd3'; import PacketizationDiagramDataHelper from './PacketizationDiagramDataHelper'; import PacketizationTCPPreProcessor from './PacketizationTCPPreProcessor'; import TCPToQlog from '@/components/filemanager/pcapconverter/tcptoqlog'; import { PreSpecEventParser } from '@/data/QlogLoader'; import PacketizationQUICPreProcessor from './PacketizationQUICPreProcessor'; import { PacketizationDirection } from './PacketizationDiagramModels'; export default class PacketizationDiagramD3Renderer { public containerID:string; public axisLocation:"top"|"bottom" = "bottom"; // public svgID:string; public rendering:boolean = false; protected svg!:any; protected tooltip!:any; protected connection!:QlogConnection; protected direction!:PacketizationDirection; protected totalHeight = 100; private dimensions:any = {}; constructor(containerID:string) { this.containerID = containerID; } public getDirection() { return this.direction; } public async render(connection:QlogConnection, direction:PacketizationDirection ):Promise<boolean> { if ( this.rendering ) { return false; } console.log("PacketizationDiagramD3Renderer:render", connection); this.rendering = true; const canContinue:boolean = this.setup(connection, direction); if ( !canContinue ) { this.rendering = false; return false; } await this.renderLive(); this.rendering = false; return true; } protected setup(connection:QlogConnection, direction:PacketizationDirection){ this.connection = connection; this.connection.setupLookupTable(); this.direction = direction; const container:HTMLElement = document.getElementById(this.containerID)!; this.dimensions.margin = {top: 30, right: Math.round(container.clientWidth * 0.05), bottom: 20, left: 100}; if ( this.axisLocation === "top" ){ this.dimensions.margin.top = 30; } else { this.dimensions.margin.bottom = 40; } // width and height are the INTERNAL widths (so without the margins) this.dimensions.width = container.clientWidth - this.dimensions.margin.left - this.dimensions.margin.right; this.dimensions.height = this.totalHeight; // clear old rendering d3.select( "#" + this.containerID ).selectAll("*").remove(); this.svg = d3.select("#" + this.containerID) .append("svg") .attr("width", this.dimensions.width + this.dimensions.margin.left + this.dimensions.margin.right) .attr("height", this.dimensions.height + this.dimensions.margin.top + this.dimensions.margin.bottom) // .attr("viewBox", [0, 0, this.dimensions.width, this.dimensions.height]) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("font-family", "Trebuchet-ms") .append("g") .attr("transform", "translate(" + this.dimensions.margin.left + "," + this.dimensions.margin.top + ")"); this.tooltip = d3.select("#packetization-packet-tooltip") .style("opacity", 0) .style("position", "absolute") .style("padding", "5px") .style("pointer-events", "none") // crucial! .style("background", "lightsteelblue"); return true; } protected async renderLive() { console.log("Rendering packetization diagram"); // const parser = this.connection.getEventParser(); // want total millisecond range in this trace, so last - first // const xMSRange = parser.load(this.connection.getEvents()[ this.connection.getEvents().length - 1 ]).absoluteTime - // parser.load(this.connection.getEvents()[0]).absoluteTime; // console.log("DEBUG MS range for this trace: ", xMSRange); let lanes = []; if ( this.connection.commonFields && this.connection.commonFields.protocol_type === "TCP_HTTP2" ) { lanes = PacketizationTCPPreProcessor.process(this.connection, this.direction); } else { // assuming QUIC_H3 lanes = PacketizationQUICPreProcessor.process(this.connection, this.direction); } let xMax = 0; if ( lanes.length > 0 && lanes[0].ranges && lanes[0].ranges.length > 0 ) { const bottomRanges = lanes[0].ranges; xMax = bottomRanges[ bottomRanges.length - 1 ].start + bottomRanges[ bottomRanges.length - 1 ].size; } console.log("PacketizationDiagram: rendering data", lanes); const clip = this.svg.append("defs").append("SVG:clipPath") .attr("id", "clip") .append("SVG:rect") .attr("width", this.dimensions.width ) .attr("height", this.dimensions.height ) .attr("x", 0 ) .attr("y", 0); const rects = this.svg.append('g') .attr("clip-path", "url(#clip)"); const packetSidePadding = 0.3; const xDomain = d3.scaleLinear() .domain([0, xMax]) .range([ 0, this.dimensions.width ]); const xAxis = this.svg.append("g"); if ( this.axisLocation === "top" ) { xAxis .call(d3.axisTop(xDomain)); } else { xAxis .attr("transform", "translate(0," + this.dimensions.height + ")") .call(d3.axisBottom(xDomain)); } // https://bl.ocks.org/d3noob/a22c42db65eb00d4e369 const mouseOver = (toString:any, data:any, index:number) => { this.tooltip.transition() .duration(100) .style("opacity", .95); const text = toString(data); this.tooltip .html( text ) .style("left", (d3.event.pageX + 15) + "px") .style("top", (d3.event.pageY - 75) + "px"); }; const mouseOut = (data:any, index:number) => { this.tooltip.transition() .duration(200) .style("opacity", 0); }; const packetHeight = this.totalHeight * (1 / lanes.length); // goal: a string like ".packet,.tlspacket,.httppacket,.streampacket", to be used when zooming to select all elements at once const allClassNames = lanes.reduce( (prev, cur) => { prev.push( "." + cur.CSSClassName ); return prev; }, new Array<string>()).join(","); for ( const [index, lane] of lanes.entries() ) { // in the lanes array, the bottom range (e.g., TCP) is on index 0, the one above that (e.g., TLS) on index 1, etc. // however, when rendering, our y=0 is on the TOP left, instead of bottom left (so e.g., the Stream info need to be on index 0, TCP on index 3) // so we have to invert the range to accurately calculate y positions const yOffsetMultiplier = (lanes.length - index) - 1; // e.g., index 3 (last in a range of 4) gets: (4 - 3) - 1 = 0, which is the top of the graph, as expected const heightModifier = (lane.heightModifier !== undefined) ? lane.heightModifier : 1; rects .selectAll("rect." + lane.CSSClassName ) .data(lane.ranges) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.start) - packetSidePadding ) .attr("y", (d:any) => (packetHeight * yOffsetMultiplier) + packetHeight * (d.isPayload ? 0 : 0.40) ) .attr("fill", (d:any) => d.color ) .style("opacity", 1) .attr("class", lane.CSSClassName) .attr("width", (d:any) => xDomain(d.start + d.size) - xDomain(d.start) + packetSidePadding * 2) .attr("height", (d:any) => heightModifier * (packetHeight * (d.isPayload ? 1 : 0.60))) .style("pointer-events", "all") .on("mouseover", (data:any, index:any) => { return mouseOver( lane.rangeToString, data, index ); }) .on("mouseout", mouseOut ); this.svg.append('g') // text .append("text") .attr("x", -5 ) .attr("y", (packetHeight * yOffsetMultiplier) + (packetHeight / 1.75) ) // 1.75 should be 2, but eyeballing says 1.75 is better .attr("dominant-baseline", "middle") .style("text-anchor", "end") .style("font-size", "14") .style("font-family", "Trebuchet MS") .attr("fill", "#000000") .text( lane.name ); } // legend this.svg.append('g') // text .append("text") .attr("x", xDomain(xMax / 2) ) .attr("y", this.dimensions.height + this.dimensions.margin.bottom - 10 ) .attr("dominant-baseline", "baseline") .style("text-anchor", "middle") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( "Bytes " + (this.direction === PacketizationDirection.sending ? "sent" : "received") ); if ( lanes[0].max_size_local ) { const localname = (this.connection.vantagePoint && this.connection.vantagePoint.type === qlog.VantagePointType.server) ? "server" : "client"; const remotename = (localname === "client") ? "server" : "client"; this.svg.append('g') // text .append("text") .attr("x", xDomain(xMax) - 450 ) .attr("y", this.dimensions.height + this.dimensions.margin.bottom - 10 ) .attr("dominant-baseline", "baseline") .style("text-anchor", "start") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( "max receiving size " + localname + ": " + lanes[0].max_size_local ); this.svg.append('g') // text .append("text") .attr("x", xDomain(xMax) ) .attr("y", this.dimensions.height + this.dimensions.margin.bottom - 10 ) .attr("dominant-baseline", "baseline") .style("text-anchor", "end") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( "max receiving size " + remotename + ": " + lanes[0].max_size_remote ); } if ( lanes[0].efficiency ) { this.svg.append('g') // text .append("text") .attr("x", xDomain(0) ) .attr("y", this.dimensions.height + this.dimensions.margin.bottom - 10 ) .attr("dominant-baseline", "baseline") .style("text-anchor", "start") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( "efficiency " + (lanes[0].efficiency * 100).toFixed(2) + "%" ); } let flowLabel = ""; if ( this.connection.vantagePoint && this.connection.vantagePoint.type === qlog.VantagePointType.server ) { if ( this.direction === PacketizationDirection.sending ) { flowLabel = "Data sent from server to client (trace vantagepoint = server)"; } else { flowLabel = "Data received by server from client (trace vantagepoint = server)"; } } else if ( this.connection.vantagePoint && this.connection.vantagePoint.type === qlog.VantagePointType.client ) { if ( this.direction === PacketizationDirection.sending ) { flowLabel = "Data sent from client to server (trace vantagepoint = client)"; } else { flowLabel = "Data received by client from server (trace vantagepoint = client)"; } } this.svg.append('g') // text .append("text") .attr("x", xDomain(xMax / 2) ) .attr("y", -10 ) // eyeballed .attr("dominant-baseline", "baseline") .style("text-anchor", "middle") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( flowLabel ); const updateChart = () => { // recover the new scale const newX = d3.event.transform.rescaleX(xDomain); // update axes with these new boundaries // xAxis./*transition().duration(200).*/call(d3.axisBottom(newX)); if ( this.axisLocation === "top" ){ xAxis.call(d3.axisTop(newX)); } else { xAxis.call(d3.axisBottom(newX)); } // update position rects .selectAll( allClassNames ) // .transition().duration(200) .attr("x", (d:any) => newX(d.start) - packetSidePadding ) // .attr("y", (d:any) => { return 50; } ) .attr("width", (d:any) => newX(d.start + d.size) - newX(d.start) + packetSidePadding * 2) // this.byteRangeRenderer.zoom( newX ); }; const zoom = d3.zoom() .scaleExtent([1, 2000]) // This control how much you can unzoom (x0.5) and zoom (x50) .translateExtent([[0, 0], [this.dimensions.width, this.dimensions.height]]) .extent([[0, 0], [this.dimensions.width, this.dimensions.height]]) .on("zoom", updateChart); this.svg.call(zoom); // if ( dataSent.length > 0 ) { // this.byteRangeRenderer.render( dataSent, 0 ); // } } }
the_stack
import { addCollectedArtwork, OwnerType } from "@artsy/cohesion" import AsyncStorage from "@react-native-community/async-storage" import { MyCollection_me } from "__generated__/MyCollection_me.graphql" import { MyCollectionArtworkListItem_artwork } from "__generated__/MyCollectionArtworkListItem_artwork.graphql" import { MyCollectionQuery } from "__generated__/MyCollectionQuery.graphql" import { EventEmitter } from "events" import { ArtworkFilterNavigator, FilterModalMode } from "lib/Components/ArtworkFilter" import { FilterData, FilterDisplayName, FilterParamName } from "lib/Components/ArtworkFilter/ArtworkFilterHelpers" import { ArtworkFiltersStoreProvider, ArtworksFiltersStore } from "lib/Components/ArtworkFilter/ArtworkFilterStore" import { useSelectedFiltersCount } from "lib/Components/ArtworkFilter/useArtworkFilters" import { ArtworksFilterHeader } from "lib/Components/ArtworkGrids/ArtworksFilterHeader" import { InfiniteScrollMyCollectionArtworksGridContainer } from "lib/Components/ArtworkGrids/InfiniteScrollArtworksGrid" import { PAGE_SIZE } from "lib/Components/constants" import { ZeroState } from "lib/Components/States/ZeroState" import { StickyTabPageFlatListContext } from "lib/Components/StickyTabPage/StickyTabPageFlatList" import { StickyTabPageScrollView } from "lib/Components/StickyTabPage/StickyTabPageScrollView" import { useToast } from "lib/Components/Toast/toastHook" import { navigate, popToRoot } from "lib/navigation/navigate" import { defaultEnvironment } from "lib/relay/createEnvironment" import { unsafe_getFeatureFlag, useDevToggle, useFeatureFlag } from "lib/store/GlobalStore" import { extractNodes } from "lib/utils/extractNodes" import { PlaceholderGrid, PlaceholderText } from "lib/utils/placeholders" import { renderWithPlaceholder } from "lib/utils/renderWithPlaceholder" import { ProvideScreenTrackingWithCohesionSchema } from "lib/utils/track" import { screen } from "lib/utils/track/helpers" import _, { filter, orderBy, uniqBy } from "lodash" import { DateTime } from "luxon" import { Banner, Button, Flex, Separator, Spacer, useSpace } from "palette" import React, { useContext, useEffect, useState } from "react" import { Platform, RefreshControl } from "react-native" import { createPaginationContainer, graphql, QueryRenderer, RelayPaginationProp } from "react-relay" import { useTracking } from "react-tracking" import { addRandomMyCollectionArtwork } from "./utils/randomMyCollectionArtwork" const RefreshEvents = new EventEmitter() const REFRESH_KEY = "refresh" export function refreshMyCollection() { RefreshEvents.emit(REFRESH_KEY) } const featureFlagKey = Platform.select({ android: "AREnableMyCollectionAndroid", ios: "AREnableMyCollectionIOS", }) as "AREnableMyCollectionIOS" | "AREnableMyCollectionAndroid" export const useEnableMyCollection = () => { return useFeatureFlag(featureFlagKey) } export function unsafe_getEnableMyCollection() { return unsafe_getFeatureFlag(featureFlagKey) } export const HAS_SEEN_MY_COLLECTION_NEW_WORKS_BANNER = "HAS_SEEN_MY_COLLECTION_NEW_WORKS_BANNER" const hasBeenShownBanner = async () => { const hasSeen = await AsyncStorage.getItem(HAS_SEEN_MY_COLLECTION_NEW_WORKS_BANNER) return hasSeen === "true" } const MyCollection: React.FC<{ relay: RelayPaginationProp me: MyCollection_me }> = ({ relay, me }) => { const { trackEvent } = useTracking() const [filterModalVisible, setFilterModalVisible] = useState(false) const filtersCount = useSelectedFiltersCount() const enabledSortAndFilter = useFeatureFlag("ARMyCollectionLocalSortAndFilter") const appliedFiltersState = ArtworksFiltersStore.useStoreState((state) => state.appliedFilters) const artworks = extractNodes(me?.myCollectionConnection) const [isRefreshing, setIsRefreshing] = useState(false) const setFilterType = ArtworksFiltersStore.useStoreActions((s) => s.setFilterTypeAction) const setSortOptions = ArtworksFiltersStore.useStoreActions((s) => s.setSortOptions) const setFilterOptions = ArtworksFiltersStore.useStoreActions((s) => s.setFilterOptions) const filterOptions = ArtworksFiltersStore.useStoreState((s) => s.filterOptions) useEffect(() => { setFilterType("local") setSortOptions([ { paramName: FilterParamName.sort, displayText: "Price Paid (High to Low)", paramValue: "local-price-paid-high-low", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy( artworks, (a) => { return a.pricePaid.minor }, "asc" ), }, { paramName: FilterParamName.sort, displayText: "Price Paid (Low to High)", paramValue: "local-price-paid-low-high", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy( artworks, (a) => { return a.pricePaid.minor }, "desc" ), }, { paramName: FilterParamName.sort, displayText: "Artwork Year (Ascending)", paramValue: "local-year-old-new", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy( artworks, (a) => { const date = DateTime.fromISO(a.date) return date.isValid ? date.toMillis() : Number.POSITIVE_INFINITY }, "asc" ), }, { paramName: FilterParamName.sort, displayText: "Artwork Year (Descending)", paramValue: "local-year-new-old", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy( artworks, (a) => { const date = DateTime.fromISO(a.date) return date.isValid ? date.toMillis() : 0 }, "desc" ), }, { paramName: FilterParamName.sort, displayText: "Alphabetical by Artist (A to Z)", paramValue: "local-alpha-a-z", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy(artworks, (a) => a.artistNames, "asc"), }, { paramName: FilterParamName.sort, displayText: "Alphabetical by Artist (Z to A)", paramValue: "local-alpha-z-a", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks) => orderBy(artworks, (a) => a.artistNames, "desc"), }, ]) setFilterOptions([ { displayText: FilterDisplayName.sort, filterType: "sort", ScreenComponent: "SortOptionsScreen", }, { displayText: FilterDisplayName.artistIDs, filterType: "artistIDs", ScreenComponent: "ArtistIDsOptionsScreen", values: uniqBy( artworks.map( (a): FilterData => ({ displayText: a.artist?.name ?? "N/A", paramName: FilterParamName.artistIDs, paramValue: a.artist?.internalID ?? "", }) ), (m) => m.paramValue ), // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks, artistIDs: string[]) => filter(artworks, (a) => artistIDs.includes(a.artist.internalID)), }, { displayText: FilterDisplayName.attributionClass, filterType: "attributionClass", ScreenComponent: "AttributionClassOptionsScreen", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks, attributionClasses: string[]) => { return filter(artworks, (a) => { if (a.attributionClass && a.attributionClass.name) { return attributionClasses.includes(a.attributionClass.name) } return false }) }, }, { displayText: FilterDisplayName.additionalGeneIDs, filterType: "additionalGeneIDs", ScreenComponent: "AdditionalGeneIDsOptionsScreen", values: uniqBy( artworks.map( (a): FilterData => ({ displayText: a.medium ?? "N/A", paramName: FilterParamName.additionalGeneIDs, paramValue: a.medium ?? undefined, }) ), (m) => m.paramValue ), // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks, mediums: string[]) => filter(artworks, (a) => mediums.includes(a.medium)), }, { displayText: FilterDisplayName.priceRange, filterType: "priceRange", ScreenComponent: "PriceRangeOptionsScreen", // tslint:disable-next-line: no-shadowed-variable localSortAndFilter: (artworks, priceRange: string) => { const splitRange = priceRange.split("-") const lowerBoundStr = splitRange[0] const upperBoundStr = splitRange[1] let lowerBound = 0 let upperBound = Number.POSITIVE_INFINITY const parsedLower = parseInt(lowerBoundStr, 10) const parsedUpper = parseInt(upperBoundStr, 10) if (!isNaN(parsedLower)) { lowerBound = parsedLower } if (!isNaN(parsedUpper)) { upperBound = parsedUpper } return filter(artworks, (a) => { if (isNaN(a.pricePaid.minor)) { return false } const pricePaid = a.pricePaid.minor / 100 return pricePaid >= lowerBound && pricePaid <= upperBound }) }, }, { displayText: FilterDisplayName.sizes, filterType: "sizes", ScreenComponent: "SizesOptionsScreen", localSortAndFilter: ( // tslint:disable-next-line: no-shadowed-variable artworks, sizeParams: { paramName: FilterParamName.width | FilterParamName.height | FilterParamName.sizes paramValue: string } ) => { if (sizeParams.paramName === "sizes") { return filter(artworks, (a) => { const size: string = a.sizeBucket return sizeParams.paramValue.includes(size.toUpperCase()) }) } else { const splitRange = sizeParams.paramValue.split("-") const lowerBoundStr = splitRange[0] const upperBoundStr = splitRange[1] let lowerBound = 0 let upperBound = Number.POSITIVE_INFINITY const parsedLower = parseInt(lowerBoundStr, 10) const parsedUpper = parseInt(upperBoundStr, 10) if (!isNaN(parsedLower)) { lowerBound = parsedLower } if (!isNaN(parsedUpper)) { upperBound = parsedUpper } return filter(artworks, (a) => { const targetMetric = sizeParams.paramName === "width" ? a.width : a.height if (isNaN(targetMetric)) { return false } return targetMetric >= lowerBound && targetMetric <= upperBound }) } }, }, ]) }, []) useEffect(() => { RefreshEvents.addListener(REFRESH_KEY, refetch) return () => { RefreshEvents.removeListener(REFRESH_KEY, refetch) } }, []) const refetch = () => { setIsRefreshing(true) relay.refetchConnection(PAGE_SIZE, (err) => { setIsRefreshing(false) if (err && __DEV__) { console.error(err) } }) } // hack for tests. we should fix that. const setJSX = __TEST__ ? jest.fn() : useContext(StickyTabPageFlatListContext).setJSX const space = useSpace() const toast = useToast() const allowOrderImports = useFeatureFlag("AREnableMyCollectionOrderImport") const showDevAddButton = useDevToggle("DTEasyMyCollectionArtworkCreation") useEffect(() => { if (artworks.length) { hasBeenShownBanner().then((hasSeenBanner) => { const showNewWorksBanner = me.myCollectionInfo?.includesPurchasedArtworks && allowOrderImports && !hasSeenBanner setJSX( <Flex> {enabledSortAndFilter ? ( <ArtworksFilterHeader selectedFiltersCount={filtersCount} onFilterPress={() => setFilterModalVisible(true)} > <Button data-test-id="add-artwork-button-non-zero-state" size="small" variant="fillDark" onPress={() => { navigate("my-collection/artworks/new", { passProps: { mode: "add", onSuccess: popToRoot, }, }) trackEvent(tracks.addCollectedArtwork()) }} haptic > Add Works </Button> </ArtworksFilterHeader> ) : ( <Flex flexDirection="row" alignSelf="flex-end" px={2} py={1}> <Button testID="add-artwork-button-non-zero-state" size="small" variant="fillDark" onPress={() => { navigate("my-collection/artworks/new", { passProps: { mode: "add", onSuccess: popToRoot, }, }) trackEvent(tracks.addCollectedArtwork()) }} haptic > Add Works </Button> </Flex> )} {!!showNewWorksBanner && ( <Banner title="You have some artworks." text="To help add your current artworks to your collection, we automatically added your purchases from your order history." showCloseButton onClose={() => AsyncStorage.setItem(HAS_SEEN_MY_COLLECTION_NEW_WORKS_BANNER, "true")} /> )} </Flex> ) }) } else { // remove already set JSX setJSX(null) } }, [artworks.length, filtersCount, enabledSortAndFilter]) return ( <ProvideScreenTrackingWithCohesionSchema info={screen({ context_screen_owner_type: OwnerType.myCollection, })} > <ArtworkFilterNavigator visible={filterModalVisible} mode={FilterModalMode.Custom} closeModal={() => setFilterModalVisible(false)} exitModal={() => setFilterModalVisible(false)} /> <StickyTabPageScrollView contentContainerStyle={{ paddingBottom: space(2) }} refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={refetch} />} > {artworks.length === 0 ? ( <ZeroState title="Your art collection in your pocket." subtitle="Keep track of your collection all in one place and get market insights" callToAction={ <Button testID="add-artwork-button-zero-state" onPress={() => { trackEvent(tracks.addCollectedArtwork()) navigate("my-collection/artworks/new", { passProps: { mode: "add", onSuccess: popToRoot, }, }) }} block > Add artwork </Button> } /> ) : ( <Flex pt={1}> <InfiniteScrollMyCollectionArtworksGridContainer myCollectionConnection={me.myCollectionConnection!} hasMore={relay.hasMore} loadMore={relay.loadMore} // tslint:disable-next-line: no-shadowed-variable localSortAndFilterArtworks={(artworks: MyCollectionArtworkListItem_artwork[]) => { let processedArtworks = artworks const filtering = uniqBy( appliedFiltersState.filter((x) => x.paramName !== FilterParamName.sort), (f) => f.paramName ) // custom size filters come back with a different type, consolidate to one const sizeFilterTypes = [FilterParamName.width, FilterParamName.height, FilterParamName.sizes] // tslint:disable-next-line: no-shadowed-variable filtering.forEach((filter) => { if (sizeFilterTypes.includes(filter.paramName)) { /* * Custom handling for size filter * 2 flavors: * a sizeRange representing either a width or height restriction OR * 1 or more size bucket names which should be matched against artwork values * pass the paramName so we can distinguish how to handle in the step */ const sizeFilterParamName = FilterParamName.sizes const sizeFilterStep = (filterOptions ?? []).find((f) => f.filterType === sizeFilterParamName)! .localSortAndFilter! processedArtworks = sizeFilterStep(processedArtworks, { paramValue: filter.paramValue, paramName: filter.paramName, }) } else { const filterStep = (filterOptions ?? []).find((f) => f.filterType === filter.paramName)! .localSortAndFilter! processedArtworks = filterStep(processedArtworks, filter.paramValue) } }) const sorting = appliedFiltersState.filter((x) => x.paramName === FilterParamName.sort) if (sorting.length > 0) { const sortStep = sorting[0].localSortAndFilter! processedArtworks = sortStep(processedArtworks) } return processedArtworks }} /> </Flex> )} {!!showDevAddButton && ( <Button onPress={async () => { toast.show("Adding artwork", "middle") await addRandomMyCollectionArtwork() toast.hideOldest() }} block > Add Random Work </Button> )} </StickyTabPageScrollView> </ProvideScreenTrackingWithCohesionSchema> ) } export const MyCollectionContainer = createPaginationContainer( MyCollection, { me: graphql` fragment MyCollection_me on Me @argumentDefinitions( excludePurchasedArtworks: { type: "Boolean", defaultValue: true } count: { type: "Int", defaultValue: 100 } cursor: { type: "String" } ) { id myCollectionInfo { includesPurchasedArtworks } myCollectionConnection( excludePurchasedArtworks: $excludePurchasedArtworks first: $count after: $cursor sort: CREATED_AT_DESC ) @connection(key: "MyCollection_myCollectionConnection", filters: []) { edges { node { id medium pricePaid { minor } attributionClass { name } sizeBucket width height artist { internalID name } } } ...InfiniteScrollArtworksGrid_myCollectionConnection @arguments(skipArtworkGridItem: true) } } `, }, { getVariables(_props, { count, cursor }, fragmentVariables) { return { ...fragmentVariables, count, cursor, } }, query: graphql` query MyCollectionPaginationQuery($excludePurchasedArtworks: Boolean, $count: Int!, $cursor: String) { me { ...MyCollection_me @arguments(excludePurchasedArtworks: $excludePurchasedArtworks, count: $count, cursor: $cursor) } } `, } ) export const MyCollectionQueryRenderer: React.FC = () => { const enableMyCollectionOrderImport = useFeatureFlag("AREnableMyCollectionOrderImport") const excludePurchasedArtworks = !enableMyCollectionOrderImport return ( <ArtworkFiltersStoreProvider> <QueryRenderer<MyCollectionQuery> environment={defaultEnvironment} query={graphql` query MyCollectionQuery($excludePurchasedArtworks: Boolean) { me { ...MyCollection_me @arguments(excludePurchasedArtworks: $excludePurchasedArtworks) } } `} variables={{ excludePurchasedArtworks }} cacheConfig={{ force: true }} render={renderWithPlaceholder({ Container: MyCollectionContainer, renderPlaceholder: () => <LoadingSkeleton />, })} /> </ArtworkFiltersStoreProvider> ) } export const LoadingSkeleton: React.FC<{}> = () => { return ( <Flex> <Flex flexDirection="row" justifyContent="space-between"> <Spacer /> <Spacer /> <PlaceholderText width={70} margin={20} /> </Flex> <Flex flexDirection="row" justifyContent="space-between" alignItems="center" px="2"> <Flex> <Spacer mb={40} /> {/* Entity name */} <PlaceholderText width={180} /> {/* subtitle text */} <PlaceholderText width={100} /> </Flex> </Flex> <Spacer mb={3} /> {/* tabs */} <Flex justifyContent="space-around" flexDirection="row" px={2}> <PlaceholderText width="40%" /> <PlaceholderText width="40%" /> </Flex> <Spacer mb={1} /> <Separator /> <Spacer mb={3} /> {/* masonry grid */} <PlaceholderGrid /> </Flex> ) } const tracks = { addCollectedArtwork, }
the_stack
import { Box, BoxProps } from "../../box"; import { ComponentProps, ElementType, MouseEvent, ReactNode, SyntheticEvent, cloneElement, forwardRef, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { FocusScopeContext, InteractionProps, InternalProps, MergedRef, OmitInternalProps, StyledComponentProps, cssModule, isNil, isString, mergeProps, normalizeSize, useAutoFocusChild, useEventCallback, useFocusManager, useFocusScope, useId, useMergedRefs, useRefState, useResizeObserver, useSlots } from "../../shared"; import { ResponsiveProp, useResponsiveValue } from "../../styling"; import { Underlay, isElementInViewport, useOverlayFocusRing, useOverlayLightDismiss, useRestoreFocus, useTrapFocus } from "../../overlay"; import { CrossButton } from "../../button"; import { Div } from "../../html"; import { Text } from "../../typography"; import { useDialogTriggerContext } from "./DialogTriggerContext"; export type AbstractDialogProps<T extends ElementType> = InternalProps & InteractionProps & Omit<StyledComponentProps<T>, "role" | "zIndex"> & { /** * React children. */ children: ReactNode; /** * Whether or not the dialog should close on outside interactions. */ dismissable?: boolean; /** * Called when a closing event happenened. * @param {SyntheticEvent} event - React's original synthetic event. * @returns {void} */ onClose?: (event: SyntheticEvent) => void; /** * Additional props to render on the wrapper element. */ wrapperProps?: Partial<BoxProps>; /** * The z-index of the dialog. */ zIndex?: number; }; const DefaultElement = "section"; export interface InnerDialogProps extends AbstractDialogProps<typeof DefaultElement> { /** * The dialog role. */ role?: "dialog" | "alertdialog"; /** * A dialog can vary in size. */ size?: ResponsiveProp<"sm" | "md" | "lg" | "fullscreen">; } function useHideBodyScrollbar() { const [stateRef, setState] = useRefState({ isVisible: true, originalPosition: "" }); useEffect(() => { if (stateRef.current.isVisible) { setState({ isVisible: false, originalPosition: document.body.style.overflowY }); document.body.style.overflowY = "hidden"; } return () => { // eslint-disable-next-line react-hooks/exhaustive-deps const state = stateRef.current; if (!state.isVisible) { setState({ isVisible: true, originalPosition: "" }); document.body.style.overflowY = state.originalPosition; } }; }, [stateRef, setState]); } function useElementHasVerticalScrollbar(): [MergedRef<HTMLElement>, boolean] { const [hasScrollbar, setHasScrollbar] = useState(false); const [elementRef, setElement] = useRefState<HTMLElement>(); const handleElementResize = useEventCallback(() => { setHasScrollbar(elementRef.current.scrollHeight > elementRef.current.clientHeight); }); const resizeRef = useResizeObserver(handleElementResize); return [ useMergedRefs(setElement, resizeRef), hasScrollbar ]; } export function InnerDialog({ "aria-describedby": ariaDescribedBy, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, as = DefaultElement, children, dismissable = true, focus, forwardedRef, id, onClose, role = "dialog", size, wrapperProps, zIndex = 10000, ...rest }: InnerDialogProps) { const sizeValue = useResponsiveValue(size); const [focusScope, setFocusRef] = useFocusScope(); const wrapperRef = useRef<HTMLElement>(); const dialogRef = useMergedRefs(forwardedRef, setFocusRef); const dismissButtonRef = useRef<HTMLButtonElement>(); const { close: triggerClose } = useDialogTriggerContext(); useHideBodyScrollbar(); const [hasVerticalScrollbarRef, wrapperHasVerticalScrollbar] = useElementHasVerticalScrollbar(); const close = useCallback(event => { if (!isNil(triggerClose)) { triggerClose(event); } if (!isNil(onClose)) { onClose(event); } }, [onClose, triggerClose]); const focusManager = useFocusManager(focusScope); useTrapFocus(focusManager); const restoreFocusProps = useRestoreFocus(focusScope); useAutoFocusChild(focusManager, { canFocus: useCallback((element: HTMLElement) => { // Do not autofocus the dialog itself. if (element === dialogRef.current) { return false; } // Do not autofocus the dismiss button. if (element === dismissButtonRef.current) { return false; } // Do not autofocus a link. if (element?.tagName === "A") { return false; } // Make sure the autofocus element is in the current viewport to prevent from scrolling down on open. if (!isElementInViewport(element)) { return false; } return true; }, [dialogRef, dismissButtonRef]), onNotFound: useEventCallback(() => { dialogRef.current?.focus(); }), tabbableOnly: true }); const focusRingProps = useOverlayFocusRing({ focus }); const overlayDismissProps = useOverlayLightDismiss(focusScope, { hideOnEscape: true, hideOnLeave: false, hideOnOutsideClick: dismissable, onHide: useEventCallback((event: SyntheticEvent) => { close(event); }) }); const handleDismissButtonClick = useEventCallback((event: MouseEvent) => { close(event); }); const dialogId = useId(id, "o-ui-dialog"); const { button, "button-group": buttonGroup, content, footer, header, heading, illustration, image } = useSlots(children, useMemo(() => ({ _: { required: ["heading", "content"] }, button: { className: "o-ui-dialog-button" }, "button-group": { className: "o-ui-dialog-button-group" }, content: { as: Text, className: "o-ui-dialog-content", id: `${dialogId}-content` }, footer: { as: "footer", className: "o-ui-dialog-footer" }, header: { as: "header", className: "o-ui-dialog-header" }, heading: { as: "h3", className: "o-ui-dialog-heading", id: `${dialogId}-heading`, size: "sm" }, illustration: { className: "o-ui-dialog-illustration", orientation: "vertical" }, image: null }), [dialogId])); const headingId = heading?.props?.id; const contentId = content?.props?.id; const imageMarkup = image && ( <Div className="o-ui-dialog-image"> {image} </Div> ); const headerMarkup = isString(header?.props?.children) ? cloneElement(header, { children: <Text>{header?.props?.children}</Text> }) : header; const footerMarkup = isString(footer?.props?.children) ? cloneElement(footer, { children: <Text>{footer?.props?.children}</Text> }) : footer; const dismissButtonMarkup = dismissable && ( <CrossButton aria-label="Dismiss" className="o-ui-dialog-dismiss-button" condensed onClick={handleDismissButtonClick} ref={dismissButtonRef} size="xs" /> ); const headerSectionMarkup = (!isNil(heading) || !isNil(headerMarkup)) && ( <Div className="o-ui-dialog-header-section"> {heading} {headerMarkup} </Div> ); const footerSectionMarkup = (!isNil(footerMarkup) || !isNil(button) || !isNil(buttonGroup)) && ( <Div className="o-ui-dialog-footer-section"> {footerMarkup} {button} {buttonGroup} </Div> ); return ( <FocusScopeContext.Provider value={{ scope: focusScope }}> <Underlay zIndex={zIndex} /> <Div {...mergeProps( wrapperProps ?? {}, { className: cssModule( "o-ui-dialog-wrapper", wrapperHasVerticalScrollbar && "scrolling" ), ref: useMergedRefs(wrapperRef, hasVerticalScrollbarRef), zIndex: zIndex + 1 } )} > <Box {...mergeProps( rest, { "aria-describedby": !isNil(ariaDescribedBy) ? ariaDescribedBy : contentId ?? undefined, "aria-label": ariaLabel, "aria-labelledby": isNil(ariaLabel) ? ariaLabelledBy ?? headingId : undefined, "aria-modal": true, as, className: cssModule( "o-ui-dialog", sizeValue === "fullscreen" ? sizeValue : normalizeSize(sizeValue), focus && "focus" ), id: dialogId, ref: dialogRef, role, tabIndex: -1 }, overlayDismissProps, focusRingProps, restoreFocusProps )} > {dismissButtonMarkup} {imageMarkup} {illustration} <Div className="o-ui-dialog-aside"> {headerSectionMarkup} {content} {footerSectionMarkup} </Div> </Box> </Div> </FocusScopeContext.Provider> ); } InnerDialog.defaultElement = DefaultElement; export const Dialog = forwardRef<any, OmitInternalProps<InnerDialogProps>>((props, ref) => ( <InnerDialog {...props} forwardedRef={ref} /> )); export type DialogProps = ComponentProps<typeof Dialog>;
the_stack
import * as vscode from "vscode"; import * as langclient from "vscode-languageclient/node"; import configuration from "../configuration"; import { getSwiftExecutable, isPathInsidePath, swiftDriverSDKFlags, swiftRuntimeEnv, } from "../utilities/utilities"; import { Version } from "../utilities/version"; import { FolderEvent, WorkspaceContext } from "../WorkspaceContext"; import { activateInlayHints } from "./inlayHints"; import { FolderContext } from "../FolderContext"; /** Manages the creation and destruction of Language clients as we move between * workspace folders */ export class LanguageClientManager { // document selector used by language client static documentSelector = [ { scheme: "file", language: "swift" }, { scheme: "untitled", language: "swift" }, { scheme: "file", language: "c" }, { scheme: "untitled", language: "c" }, { scheme: "file", language: "cpp" }, { scheme: "untitled", language: "cpp" }, { scheme: "file", language: "objective-c" }, { scheme: "untitled", language: "objective-c" }, { scheme: "file", language: "objective-cpp" }, { scheme: "untitled", language: "objective-cpp" }, ]; /** current running client */ private languageClient: langclient.LanguageClient | null | undefined; private cancellationToken?: vscode.CancellationTokenSource; private observeFoldersDisposable: vscode.Disposable; private onDidCreateFileDisposable: vscode.Disposable; private onDidDeleteFileDisposable: vscode.Disposable; private onChangeConfig: vscode.Disposable; private inlayHints?: vscode.Disposable; private supportsDidChangedWatchedFiles: boolean; private startedPromise?: Promise<void>; private currentWorkspaceFolder?: vscode.Uri; private waitingOnRestartCount: number; public documentSymbolWatcher?: ( document: vscode.TextDocument, symbols: vscode.DocumentSymbol[] | null | undefined ) => void; constructor(public workspaceContext: WorkspaceContext) { // stop and start server for each folder based on which file I am looking at this.observeFoldersDisposable = workspaceContext.observeFolders( async (folderContext, event) => { switch (event) { case FolderEvent.add: if (folderContext && folderContext.folder) { // if active document is inside folder then setup language client if (this.isActiveFileInFolder(folderContext.folder)) { await this.setLanguageClientFolder(folderContext.folder); } } break; case FolderEvent.focus: await this.setLanguageClientFolder(folderContext?.folder); break; } } ); // restart LSP server on creation of a new file this.onDidCreateFileDisposable = vscode.workspace.onDidCreateFiles(() => { if (!this.supportsDidChangedWatchedFiles) { this.restartLanguageClient(); } }); // restart LSP server on deletion of a file this.onDidDeleteFileDisposable = vscode.workspace.onDidDeleteFiles(() => { if (!this.supportsDidChangedWatchedFiles) { this.restartLanguageClient(); } }); // on change config restart server this.onChangeConfig = vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration("sourcekit-lsp.serverPath")) { vscode.window .showInformationMessage( "Changing LSP server path requires the language server be restarted.", "Ok" ) .then(selected => { if (selected === "Ok") { this.restartLanguageClient(); } }); } }); // if we are running swift 5.6 or greater then LSP supports `didChangeWatchedFiles` message this.supportsDidChangedWatchedFiles = workspaceContext.swiftVersion.isGreaterThanOrEqual( new Version(5, 6, 0) ); this.waitingOnRestartCount = 0; this.documentSymbolWatcher = undefined; this.cancellationToken = new vscode.CancellationTokenSource(); } dispose() { this.cancellationToken?.cancel(); this.cancellationToken?.dispose(); this.observeFoldersDisposable.dispose(); this.onDidCreateFileDisposable?.dispose(); this.onDidDeleteFileDisposable?.dispose(); this.onChangeConfig.dispose(); this.inlayHints?.dispose(); this.languageClient?.stop(); } /** Set folder for LSP server * * If server is already running then check if the workspace folder is the same if * it isn't then restart the server using the new workspace folder. */ async setLanguageClientFolder(uri?: vscode.Uri, forceRestart = false) { if (this.languageClient === undefined) { this.currentWorkspaceFolder = uri; this.startedPromise = this.setupLanguageClient(uri); return; } else { if (uri === undefined || (this.currentWorkspaceFolder === uri && !forceRestart)) { return; } // count number of setLanguageClientFolder calls waiting on startedPromise this.waitingOnRestartCount += 1; // if in the middle of a restart then we have to wait until that // restart has finished if (this.startedPromise) { try { await this.startedPromise; } catch (error) { //ignore error } } this.waitingOnRestartCount -= 1; // only continue if no more calls are waiting on startedPromise if (this.waitingOnRestartCount !== 0) { return; } const client = this.languageClient; // language client is set to null while it is in the process of restarting this.languageClient = null; this.currentWorkspaceFolder = uri; this.inlayHints?.dispose(); this.inlayHints = undefined; if (client) { this.cancellationToken?.cancel(); this.cancellationToken?.dispose(); this.startedPromise = client .stop() .then(async () => { // if force restart is set then rebuild client completely // before starting otherwise just set the workspace folder // and call `startClient` if (forceRestart) { await this.setupLanguageClient(uri); } else { // change workspace folder and restart const workspaceFolder = { uri: uri, name: FolderContext.uriName(uri), index: 0, }; client.clientOptions.workspaceFolder = workspaceFolder; await this.startClient(client); } }) .catch(reason => { this.workspaceContext.outputChannel.log(`${reason}`); }); } } } /** * Use language client safely. Provides a cancellation token to the function * which can be used to safely ensure language client request are cancelled * if the language is shutdown. * @param process process using language client * @returns result of process */ async useLanguageClient<Return>(process: { (client: langclient.LanguageClient, cancellationToken: vscode.CancellationToken): Return; }) { if (!this.languageClient) { throw LanguageClientError.LanguageClientUnavailable; } return await this.languageClient.onReady().then(() => { if (!this.languageClient || !this.cancellationToken) { throw LanguageClientError.LanguageClientUnavailable; } return process(this.languageClient, this.cancellationToken.token); }); } /** Restart language client */ async restartLanguageClient() { // force restart of language client await this.setLanguageClientFolder(this.currentWorkspaceFolder, true); } private isActiveFileInFolder(uri: vscode.Uri): boolean { if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document) { // if active document is inside folder then setup language client const activeDocPath = vscode.window.activeTextEditor.document.uri.fsPath; if (isPathInsidePath(activeDocPath, uri.fsPath)) { return true; } } return false; } private async setupLanguageClient(folder?: vscode.Uri): Promise<void> { const client = await this.createLSPClient(folder); await this.startClient(client); } private async createLSPClient(folder?: vscode.Uri): Promise<langclient.LanguageClient> { const lspConfig = configuration.lsp; const serverPathConfig = lspConfig.serverPath; const serverPath = serverPathConfig.length > 0 ? serverPathConfig : getSwiftExecutable("sourcekit-lsp"); const sdkArguments = swiftDriverSDKFlags(true); const sourcekit: langclient.Executable = { command: serverPath, args: lspConfig.serverArguments.concat(sdkArguments), options: { env: { ...process.env, ...swiftRuntimeEnv() } }, }; // if path to LSP server is not equal to the path to swift and both are set, then // pass swift toolchain to the LSP server if ( serverPathConfig.length > 0 && configuration.path.length > 0 && serverPathConfig !== getSwiftExecutable("sourcekit-lsp") ) { const toolchainPath = this.workspaceContext.toolchain.toolchainPath; if (toolchainPath) { // eslint-disable-next-line @typescript-eslint/naming-convention sourcekit.options = { env: { ...sourcekit.options?.env, SOURCEKIT_TOOLCHAIN_PATH: toolchainPath }, }; } } const serverOptions: langclient.ServerOptions = sourcekit; let workspaceFolder = undefined; if (folder) { workspaceFolder = { uri: folder, name: FolderContext.uriName(folder), index: 0 }; } const clientOptions: langclient.LanguageClientOptions = { documentSelector: LanguageClientManager.documentSelector, revealOutputChannelOn: langclient.RevealOutputChannelOn.Never, workspaceFolder: workspaceFolder, middleware: { provideDocumentSymbols: async (document, token, next) => { const result = await next(document, token); const documentSymbols = result as vscode.DocumentSymbol[]; if (this.documentSymbolWatcher && documentSymbols) { this.documentSymbolWatcher(document, documentSymbols); } return result; }, }, }; return new langclient.LanguageClient( "sourcekit-lsp", "SourceKit Language Server", serverOptions, clientOptions ); } private async startClient(client: langclient.LanguageClient) { client.start(); if (client.clientOptions.workspaceFolder) { this.workspaceContext.outputChannel.log( `SourceKit-LSP setup for ${FolderContext.uriName( client.clientOptions.workspaceFolder.uri )}` ); } else { this.workspaceContext.outputChannel.log(`SourceKit-LSP setup`); } this.languageClient = client; this.cancellationToken = new vscode.CancellationTokenSource(); return new Promise<void>((resolve, reject) => { client .onReady() .then(() => { this.inlayHints = activateInlayHints(client); resolve(); }) .catch(reason => { this.workspaceContext.outputChannel.log(`${reason}`); // if language client failed to initialise then shutdown and set to undefined this.languageClient?.stop(); this.languageClient = undefined; reject(reason); }); }); } } /** Language client errors */ export enum LanguageClientError { LanguageClientUnavailable, }
the_stack
export interface OutputDescribeRiskModel { /** * 请求返回状态值,0为成功,别的结合Message查看 注意:此字段可能返回 null,表示取不到有效值。 */ Code: number; /** * 请求返回信息 */ Message: string; /** * 请求返回结果 */ Value: OutputDescribeRiskModelValue; } /** * QQ账号信息。 */ export interface QQAccountInfo { /** * QQ的OpenID。 */ QQOpenId: string; /** * QQ分配给网站或应用的AppId,用来唯一标识网站或应用。 */ AppIdUser: string; /** * 用于标识QQ用户登录后所关联业务自身的账号ID。 */ AssociateAccount?: string; /** * 账号绑定的手机号。 */ MobilePhone?: string; /** * 用户设备号。 */ DeviceId?: string; } /** * ManageMarketingRisk请求参数结构体 */ export interface ManageMarketingRiskRequest { /** * 业务入参 */ BusinessSecurityData: InputManageMarketingRisk; } /** * 全栈式风控引擎出参 */ export interface OutputManageMarketingRisk { /** * 返回码。0表示成功,非0标识失败错误码。 注意:此字段可能返回 null,表示取不到有效值。 */ Code: number; /** * UTF-8编码,出错消息。 注意:此字段可能返回 null,表示取不到有效值。 */ Message: string; /** * 业务详情。 注意:此字段可能返回 null,表示取不到有效值。 */ Value: OutputManageMarketingRiskValue; /** * 控制台显示的req_id。 注意:此字段可能返回 null,表示取不到有效值。 */ UUid: string; } /** * 诈骗信息。 */ export interface OnlineScamInfo { /** * 内容标签。 */ ContentLabel?: string; /** * 内容风险等级: 0:正常。 1:可疑。 */ ContentRiskLevel?: number; /** * 内容产生形式: 0:对话。 1:广播。 */ ContentType?: number; /** * 诈骗账号类型: 1:11位手机号。 2:QQ账号。 */ FraudType?: number; /** * 诈骗账号,手机号或QQ账号。 */ FraudAccount?: string; } /** * 全栈式风控引擎入参 */ export interface InputManageMarketingRisk { /** * 账号信息。 */ Account: AccountInfo; /** * 场景类型:场景SceneCode, 控制台上新建对应的场景并获取对应的值; 例如:e_register_protection_1521184361 控制台链接:https://console.cloud.tencent.com/rce/risk/sceneroot; */ SceneCode: string; /** * 登录来源的外网IP */ UserIp: string; /** * 用户操作时间戳,单位秒(格林威治时间精确到秒,如1501590972)。 */ PostTime: number; /** * 用户唯一标识。 */ UserId?: string; /** * 设备指纹token。 */ DeviceToken?: string; /** * 设备指纹BusinessId */ DeviceBusinessId?: number; /** * 业务ID。网站或应用在多个业务中使用此服务,通过此ID区分统计数据。 */ BusinessId?: number; /** * 昵称,UTF-8 编码。 */ Nickname?: string; /** * 用户邮箱地址(非系统自动生成)。 */ EmailAddress?: string; /** * 是否识别设备异常: 0:不识别。 1:识别。 */ CheckDevice?: number; /** * 用户HTTP请求中的Cookie进行2次hash的值,只要保证相同Cookie的hash值一致即可。 */ CookieHash?: string; /** * 用户HTTP请求的Referer值。 */ Referer?: string; /** * 用户HTTP请求的User-Agent值。 */ UserAgent?: string; /** * 用户HTTP请求的X-Forwarded-For值。 */ XForwardedFor?: string; /** * MAC地址或设备唯一标识。 */ MacAddress?: string; /** * 手机制造商ID,如果手机注册,请带上此信息。 */ VendorId?: string; /** * 设备类型: 1:Android 2:IOS */ DeviceType?: number; /** * 详细信息 FieldName 清单 Android serial_number String 否 设备序列号 Android carrier String 否 运营商;-1: 获取失败,0: 其他,1: 移动,2: 联通,3: 电信,4: 铁通 Android mcc_mnc String 否 netOperator MCC+MNC Android model String 否 手机型号 Android os_system String 否 操作系统 Android vendor_id String 否 设备品牌 “华为”“oppo”“小米” Android device_version String 否 设备版本 Android android_api_level String 否 安卓API等级 Android phone_chip_info String 否 手机芯片信息 Android resolution_w String 否 屏幕分辨率宽,保留整数 Android resolution_h String 否 屏幕分辨率高,保留整数 Android brightness String 否 屏幕亮度 Android bluetooth_address String 否 蓝牙地址 Android baseband_version String 否 基带版本 Android kernel_version String 否 kernel 版本 Android cpu_core String 否 CPU 核数 Android cpu_model String 否 CPU 型号 Android memory String 否 内存容量,单位转换为 GB Android storage String 否 存储容量,单位转换为 GB Android volume String 否 手机音量 Android battery_power String 否 电池电量 Android language String 否 语言 Android package_name String 否 软件包名 Android App_version String 否 App 版本号 Android App_name String 否 App 显示名称 Android is_debug String 否 是否 debug;0 为正常模式,1 为 debug 模式;其他值无效 Android is_root String 否 是否越狱;0 为正常,1 为越狱;其他值无效 Android is_proxy String 否 是否启动代理;0 为未开启,1 为开启;其他值无效 Android is_emulator String 否 是否模拟器;0 为未开启,1 为开启;其他值无效 Android charge_status String 否 充电状态;1-不在充电,2-USB充电,3-电源充电 Android network_type String 否 网络类型:2G/3G/4G/5G/WiFi/WWAN/other Android wifi_mac String 否 WiFi MAC地址 IOS model String 否 机器型号 iPhone11 IOS memory String 否 内存容量,单位转换为 GB IOS os_system String 否 操作系统 IOS device_version String 否 设备版本 IOS phone_chip_info String 否 手机芯片信息 IOS device_name String 否 设备名称 "xxx 的 iPhone","xxx's IPhone" 等等 IOS uptime String 否 开机时间 IOS language String 否 系统语言 IOS carrier String 否 运营商 IOS cpu_model String 否 CPU 型号 IOS cpu_core String 否 CPU 个数 IOS volume String 否 手机音量 IOS battery_power String 否 电池电量 IOS resolution_w String 否 屏幕分辨率宽,保留整数 IOS resolution_h String 否 屏幕分辨率高,保留整数 IOS package_name String 否 App 包名 IOS App_version String 否 App 版本号 IOS App_name String 否 App 显示名称 IOS is_debug String 否 是否 debug;0 为正常模式,1 为 debug 模式;其他值无效 IOS is_root String 否 是否越狱;0 为正常,1 为越狱;其他值无效 IOS is_proxy String 否 是否启动代理;0 为未开启,1 为开启;其他值无效 IOS is_emulator String 否 是否模拟器;0 为未开启,1 为开启;其他值无效 IOS charge_status String 否 充电状态;1-不在充电,2-USB充电,3-电源充电 IOS network_type String 否 网络类型:2G/3G/4G/5G/WiFi/WWAN/other IOS wifi_mac String 否 WiFi MAC地址 其他 os_system String 否 操作系统 其他 browser String 否 浏览器信息 其他 from_url String 否 来源链接 */ Details?: Array<InputDetails>; /** * 可选填写。详情请跳转至SponsorInfo查看。 */ Sponsor?: SponsorInfo; /** * 可选填写。详情请跳转至OnlineScamInfo查看。 */ OnlineScam?: OnlineScamInfo; } /** * 其它账号信息。 */ export interface OtherAccountInfo { /** * 其它账号信息: AccountType是4时,填入真实的手机号(如13123456789)。 AccountType是8时,支持 imei、idfa、imeiMD5、idfaMD5 入参。 AccountType是0时,填入账号信息。 AccountType是10004时,填入手机号的MD5值。 注:imeiMd5 加密方式为:imei 明文小写后,进行 MD5 加密,加密后取小写值。IdfaMd5 加密方式为:idfa 明文大写后,进行 MD5 加密,加密后取小写值。 */ AccountId: string; /** * 手机号,若 AccountType 是4(手机号)、或10004(手机号 MD5),则无需重复填写,否则填入对应的手机号(如13123456789)。 */ MobilePhone?: string; /** * 用户设备号。若 AccountType 是8(设备号),则无需重复填写,否则填入对应的设备号。 */ DeviceId?: string; } /** * DescribeRiskModel返回参数结构体 */ export interface DescribeRiskModelResponse { /** * 业务出参 */ Data: OutputDescribeRiskModel; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 账号信息。 */ export interface AccountInfo { /** * 用户账号类型(默认开通 QQ 开放账号、手机号,手机 MD5 账号类型查询。如需使用微信开放账号,则需要 提交工单 由腾讯云进行资格审核,审核通过后方可正常使用微信开放账号): 1:QQ开放账号。 2:微信开放账号。 4:手机号(暂仅支持国内手机号)。 8:设备号(imei/imeiMD5/idfa/idfaMD5)。 0:其他。 10004:支持手机号MD5加密和sha256加密; 标准中国大陆手机号11位,MD5加密后取长度32位小写字符串;例如:手机号13112345678的Md5加密结果为手"dafc728802534d51fbf85c70313a2bd2" 标准中国大陆手机号11位,sha256加密后取长度为64位的小写字符串;例如:手机号13112345678的sha256加密的结果为“9f46715cff1a9ac969ec01924111f7f3697a97ad98a4fd53e15a78d79d1f3551” */ AccountType: number; /** * QQ账号信息,AccountType是1时,该字段必填。 */ QQAccount?: QQAccountInfo; /** * 微信账号信息,AccountType是2时,该字段必填。 */ WeChatAccount?: WeChatAccountInfo; /** * 其它账号信息,AccountType是0、4、8或10004时,该字段必填。 */ OtherAccount?: OtherAccountInfo; } /** * 风控建模服务出参对应值 */ export interface OutputDescribeRiskModelValue { /** * 模型分数值 */ ApplyScore: number; } /** * DescribeRiskModel请求参数结构体 */ export interface DescribeRiskModelRequest { /** * 业务入参 */ BusinessSecurityData: InputDescribeRiskModelData; } /** * 网赚防刷相关参数 */ export interface SponsorInfo { /** * 助力场景建议填写:活动发起人微信OpenID。 */ SponsorOpenId?: string; /** * 助力场景建议填写:发起人设备号。 */ SponsorDeviceNumber?: string; /** * 助力场景建议填写:发起人手机号。 */ SponsorPhone?: string; /** * 助力场景建议填写:发起人IP。 */ SponsorIp?: string; /** * 助力场景建议填写:活动链接。 */ CampaignUrl?: string; } /** * ManageMarketingRisk返回参数结构体 */ export interface ManageMarketingRiskResponse { /** * 业务出参 */ Data: OutputManageMarketingRisk; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 入参的详细参数信息 */ export interface InputDetails { /** * 字段名称 */ FieldName: string; /** * 字段值 */ FieldValue: string; } /** * 全栈式风控引擎出参值 */ export interface OutputManageMarketingRiskValue { /** * 账号ID。对应输入参数: AccountType是1时,对应QQ的OpenID。 AccountType是2时,对应微信的OpenID/UnionID。 AccountType是4时,对应手机号。 AccountType是8时,对应imei、idfa、imeiMD5或者idfaMD5。 AccountType是0时,对应账号信息。 AccountType是10004时,对应手机号的MD5。 注意:此字段可能返回 null,表示取不到有效值。 */ UserId: string; /** * 操作时间戳,单位秒(对应输入参数)。 注意:此字段可能返回 null,表示取不到有效值。 */ PostTime: number; /** * 对应输入参数,AccountType 是 QQ 或微信开放账号时,用于标识 QQ 或微信用户登录后关联业务自身的账号ID。 注意:此字段可能返回 null,表示取不到有效值。 */ AssociateAccount: string; /** * 操作来源的外网IP(对应输入参数)。 注意:此字段可能返回 null,表示取不到有效值。 */ UserIp: string; /** * 风险值 pass : 无恶意 review:需要人工审核 reject:拒绝,高风险恶意 注意:此字段可能返回 null,表示取不到有效值。 */ RiskLevel: string; /** * 风险类型,请参考官网风险类型 账号风险 1 账号信用低,账号近期存在因恶意被处罚历史,网络低活跃,被举报等因素 11 疑似 低活跃账号,账号活跃度与正常用户有差异 2 垃圾账号 疑似批量注册小号,近期存在严重违规或大量举报 21 疑似小号 账号有疑似线上养号,小号等行为 22 疑似违规账号 账号曾有违规行为、曾被举报过、曾因违规被处罚过等 3 无效账号 送检账号参数无法成功解析,请检查微信 openid 是否有误/appid与QQopenid无法关联/微信openid权限是否有开通/手机号是否为中国大陆手机号; 4 黑名单 该账号在业务侧有过拉黑记录 5 白名单 业务自行有添加过白名单记录 行为风险 101 批量操作 存在 ip/设备/环境等因素的聚集性异常 1011 疑似 IP 属性聚集,出现 IP 聚集 1012 疑似 设备属性聚集 出现设备聚集 102 自动机 疑似自动机批量请求 103 恶意行为-网赚 疑似网赚 104 微信登录态无效 检查 WeChatAccessToken 参数,是否已经失效; 201 环境风险 环境异常 操作 ip/设备/环境存在异常。当前 ip 为非常用 ip 或恶意 ip 段 2011 疑似 非常用IP 请求 当前请求 IP 非该账号常用 IP 2012 疑似 IP 异常 使用 idc 机房 ip 或 使用代理 ip 或 使用恶意 ip 等 205 非公网有效ip 传进来的 IP 地址为内网 ip 地址或者 ip 保留地址; 设备风险 206 设备异常 该设备存在异常的使用行为 2061 疑似 非常用设备 当前请求的设备非该账号常用设备 2062 疑似 虚拟设备 请求设备为模拟器、脚本、云设备等虚拟设备 2063 疑似 群控设备 请求设备为猫池、手机墙等群控设备 注意:此字段可能返回 null,表示取不到有效值。 */ RiskType: Array<number>; } /** * 微信账号信息。 */ export interface WeChatAccountInfo { /** * 微信的OpenID/UnionID 。 */ WeChatOpenId: string; /** * 微信开放账号类型: 1:微信公众号/微信第三方登录。 2:微信小程序。 */ WeChatSubType?: number; /** * 随机串。如果WeChatSubType是2,该字段必填。Token签名随机数,建议16个字符。 */ RandStr?: string; /** * 如果WeChatSubType是1,填入授权的access_token(注意:不是普通access_token,详情请参阅官方说明文档。获取网页版本的access_token时,scope字段必需填写snsapi_userinfo。 如果WeChatSubType是2,填入以session_key为密钥签名随机数RandStr(hmac_sha256签名算法)得到的字符串。 */ WeChatAccessToken?: string; /** * 用于标识微信用户登录后所关联业务自身的账号ID。 */ AssociateAccount?: string; /** * 账号绑定的手机号。 */ MobilePhone?: string; /** * 用户设备号。 */ DeviceId?: string; } /** * 客户请求入参 */ export interface InputDescribeRiskModelData { /** * 业务参数加密后的签名值 */ UserData: string; /** * 调用时间戳,精确到秒 */ ApplyDate: number; /** * 客户业务侧标识用户的唯一ID */ UserId: string; }
the_stack
import UAParser from "ua-parser-js"; import * as defs from "./types/jsonx/index"; declare global { interface window {} } var global: any = typeof global !== "undefined" ? global : typeof globalThis !== "undefined" ? globalThis : {}; /** * Used to evaluate whether or not to render a component * @param {Object} options * @param {Object} options.jsonx - Valid JSONX JSON * @param {Object} options.props - Props to test comparison values against, usually Object.assign(jsonx.props,jsonx.asyncprops,jsonx.thisprops,jsonx.windowprops) * @returns {Boolean} returns true if all comparisons are true or if using or comparisons, at least one condition is true * @example const sampleJSONX = { component: 'div', props: { id: 'generatedJSONX', className: 'jsonx', bigNum: 1430931039, smallNum: 0.425, falsey: false, truthy: true, }, children: 'some div', }; const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy',], operation:'==', right:['falsey',], }], }); displayComponent({ jsonx: testJSONX, props: testJSONX2.props, }) // => false */ export function displayComponent( options: { jsonx?: defs.jsonx; props?: any; renderIndex?: number; componentLibraries?: defs.jsonxLibrary; debug?: boolean; } = {} ): boolean { const { jsonx = {}, props } = options; const propsToCompare = jsonx.comparisonprops; const comparisons = Array.isArray(propsToCompare) ? propsToCompare.map(comp => { const compares: defs.jsonxCompare = {}; if (Array.isArray(comp.left)) { compares.left = comp.left; } if (Array.isArray(comp.right)) { compares.right = comp.right; } const propcompares = traverse(compares, props || jsonx.props); const opscompares = Object.assign({}, comp, propcompares); // console.debug({ opscompares, compares, renderedCompProps }); switch (opscompares.operation) { case "eq": case "==": // return opscompares.left == opscompares.right; // eslint-disable-next-line return opscompares.left == opscompares.right; case "dneq": case "!=": case "!": // return opscompares.left != opscompares.right; return opscompares.left !== opscompares.right; case "dnseq": case "!==": return opscompares.left !== opscompares.right; case "seq": case "===": return opscompares.left === opscompares.right; case "lt": case "<": return opscompares.left < opscompares.right; case "lte": case "<=": return opscompares.left <= opscompares.right; case "gt": case ">": return opscompares.left > opscompares.right; case "gte": case ">=": return opscompares.left >= opscompares.right; case "dne": case "undefined": case "null": return opscompares.left === undefined || opscompares.left === null; case "!null": case "!undefined": case "exists": default: //'exists' return opscompares.left !== undefined && opscompares.left !== null; } // } // if (opscompares.operation === 'eq') { // // return opscompares.left == opscompares.right; // // eslint-disable-next-line // return opscompares.left == opscompares.right; // } else if (opscompares.operation === 'dneq') { // // return opscompares.left != opscompares.right; // return opscompares.left !== opscompares.right; // } else if (opscompares.operation === 'dnseq') { // return opscompares.left !== opscompares.right; // } else if (opscompares.operation === 'seq') { // return opscompares.left === opscompares.right; // } else if (opscompares.operation === 'lt') { // return opscompares.left < opscompares.right; // } else if (opscompares.operation === 'lte') { // return opscompares.left <= opscompares.right; // } else if (opscompares.operation === 'gt') { // return opscompares.left > opscompares.right; // } else if (opscompares.operation === 'gte') { // return opscompares.left >= opscompares.right; // } else if (opscompares.operation === 'dne') { // return opscompares.left === undefined || opscompares.left === null; // } else { //'exists' // return opscompares.left !== undefined && opscompares.left !== null; // } }) : []; const validProps = comparisons.filter(comp => comp === true); if (!jsonx.comparisonprops) { return true; } else if (jsonx.comparisonorprops && validProps.length < 1) { return false; } else if ( validProps.length !== comparisons.length && !jsonx.comparisonorprops ) { return false; } else { return true; } } /** * Use to test if can bind components this context for react-redux-router * @returns {Boolean} true if browser is not IE or old android / chrome */ export function getAdvancedBinding(this: defs.globalThisWindow): boolean { var window: any = window; if (typeof window === "undefined") { if (this && this.window) { window = this.window; } else if (typeof global !== "undefined" && global.window) { window = global.window; } else if (typeof globalThis !== "undefined" && globalThis.window) { window = globalThis.window; } if (!window || !window.navigator) return false; } try { if ( window && window.navigator && window.navigator.userAgent && typeof window.navigator.userAgent === "string" ) { // console.log('window.navigator.userAgent',window.navigator.userAgent) if (window.navigator.userAgent.indexOf("Trident") !== -1) { return false; } const uastring = window.navigator.userAgent; //@ts-ignore const parser = new UAParser(); parser.setUA(uastring); const parseUserAgent = parser.getResult(); // console.log({ parseUserAgent, }); if ( (parseUserAgent.browser.name === "Chrome" || parseUserAgent.browser.name === "Chrome WebView") && parseUserAgent.os.name === "Android" && parseInt(parseUserAgent.browser.version, 10) < 50 ) { return false; } if (parseUserAgent.browser.name === "Android Browser") { return false; } } } catch (e) { e; console.error(e); // console.warn('could not detect browser support', e); return false; } return true; } /** * take an object of array paths to traverse and resolve * @example * const testObj = { user: { name: 'jsonx', description: 'react withouth javascript', }, stats: { logins: 102, comments: 3, }, authentication: 'OAuth2', }; const testVals = { auth: ['authentication', ], username: ['user', 'name', ], }; traverse(testVals, testObj) // =>{ auth:'OAuth2', username:'jsonx', } * @param {Object} paths - an object to resolve array property paths * @param {Object} data - object to traverse * @returns {Object} resolved object with traversed properties * @throws {TypeError} */ export function traverse(paths: defs.traversePaths = {}, data = {}) { let keys = Object.keys(paths); if (!keys.length) return paths; return keys.reduce((result: defs.jsonxResourceProps, key: string) => { //@ts-ignore if (typeof paths[key] === "string") result[key] = data[paths[key]]; else if (Array.isArray(paths[key])) { let _path = Object.assign([], paths[key]); let value = data; while (_path.length && value && typeof value === "object") { let prop = _path.shift(); //@ts-ignore value = value[prop]; } result[key] = _path.length ? undefined : value; } else throw new TypeError( "dynamic property paths must be a string or an array of strings or numeric indexes" ); return result; }, {}); } /** * Validates JSONX JSON Syntax * @example * validateJSONX({component:'p',children:'hello world'})=>true * validateJSONX({children:'hello world'})=>throw SyntaxError('[0001] Missing React Component') * @param {Object} jsonx - JSONX JSON to validate * @param {Boolean} [returnAllErrors=false] - flag to either throw error or to return all errors in an array of errors * @returns {Boolean|Error[]} either returns true if JSONX is valid, or throws validation error or returns list of errors in array * @throws {SyntaxError|TypeError|ReferenceError} */ export function validateJSONX( jsonx: defs.jsonx = {}, returnAllErrors = false ): boolean | string { const dynamicPropsNames = [ "asyncprops", "resourceprops", "windowprops", "thisprops", "thisstate", "thiscontext" ]; const evalPropNames = [ "__dangerouslyEvalProps", "__dangerouslyBindEvalProps" ]; const validKeys = [ "component", "props", "test", "children", "__spreadComponent", "__inline", "__functionargs", "__dangerouslyInsertComponents", "__dangerouslyInsertComponentProps", "__dangerouslyInsertJSONXComponents", "__functionProps", "__functionparams", "__windowComponents", "__windowComponentProps", "comparisonprops", "comparisonorprops", "passprops", "removeprops", "includeprops", "exposeprops", "useformregister", "debug", "___stringifyChildren", "___toStringChildren", "___toNumeral", "___FromLuxonTimeZone", "___ISOtoLuxonString", "___JSDatetoLuxonString", "___template" ].concat(dynamicPropsNames, evalPropNames); let errors: any = []; if (!jsonx.component) { errors.push(SyntaxError("[0001] Missing React Component")); } if (jsonx.props) { if (typeof jsonx.props !== "object" || Array.isArray(jsonx.props)) { errors.push( TypeError( "[0002] " + jsonx.component + ": props must be an Object / valid React props" ) ); } if ( jsonx.props.children && (typeof jsonx.props.children !== "string" || !Array.isArray(jsonx.props.children)) ) { errors.push( TypeError( "[0003] " + jsonx.component + ": props.children must be an array of JSONX JSON objects or a string" ) ); } if ( jsonx.props._children && (typeof jsonx.props._children !== "string" || !Array.isArray(jsonx.props._children)) ) { errors.push( TypeError( "[0004] " + jsonx.component + ": props._children must be an array of JSONX JSON objects or a string" ) ); } } if (jsonx.children) { if (typeof jsonx.children !== "string" && !Array.isArray(jsonx.children)) { errors.push( TypeError( "[0005] " + jsonx.component + ": children must be an array of JSONX JSON objects or a string" ) ); } if (Array.isArray(jsonx.children)) { const childrenErrors = jsonx.children .filter(c => typeof c === "object") .map(c => validateJSONX(c, returnAllErrors)); errors = errors.concat(...childrenErrors); } } dynamicPropsNames.forEach(dynamicprop => { const jsonxDynamicProps = jsonx[dynamicprop]; if (jsonxDynamicProps) { // if (dynamicprop === 'thisprops') { // console.log({ dynamicprop, jsonxDynamicProps }); // } if (typeof jsonxDynamicProps !== "object") { errors.push(TypeError(`[0006] ${dynamicprop} must be an object`)); } Object.keys(jsonxDynamicProps).forEach(resolvedDynamicProp => { if (!Array.isArray(jsonxDynamicProps[resolvedDynamicProp])) { errors.push( TypeError( `[0007] jsonx.${dynamicprop}.${resolvedDynamicProp} must be an array of strings` ) ); } if (Array.isArray(jsonxDynamicProps[resolvedDynamicProp])) { const allStringArray = jsonxDynamicProps[resolvedDynamicProp].filter( (propArrayItem: any) => typeof propArrayItem === "string" ); if ( allStringArray.length !== jsonxDynamicProps[resolvedDynamicProp].length ) { errors.push( TypeError( `[0008] jsonx.${dynamicprop}.${resolvedDynamicProp} must be an array of strings` ) ); } } }); } }); const evalProps = jsonx.__dangerouslyEvalProps; const boundEvalProps = jsonx.__dangerouslyBindEvalProps; if (evalProps || boundEvalProps) { if ( (evalProps && typeof evalProps !== "object") || (boundEvalProps && typeof boundEvalProps !== "object") ) { errors.push( TypeError( "[0009] __dangerouslyEvalProps must be an object of strings to convert to valid javascript" ) ); } evalPropNames .filter(evalProp => jsonx[evalProp]) .forEach(eProps => { const evProp = jsonx[eProps]; const scopedEval = eval; Object.keys(evProp).forEach(propToEval => { if (typeof evProp[propToEval] !== "string") { errors.push( TypeError(`[0010] jsonx.${eProps}.${evProp} must be a string`) ); } try { // console.log({ eProps }); if (eProps === "__dangerouslyBindEvalProps") { const funcToBind = scopedEval(`(${evProp[propToEval]})`); funcToBind.call({ bounded: true }); } else { scopedEval(evProp[propToEval]); } } catch (e) { errors.push(e); } }); }); } if (jsonx.__dangerouslyInsertComponents) { Object.keys(jsonx.__dangerouslyInsertComponents).forEach( insertedComponents => { try { if (jsonx.__dangerouslyInsertComponents) validateJSONX( jsonx.__dangerouslyInsertComponents[insertedComponents] ); } catch (e) { errors.push( TypeError( `[0011] jsonx.__dangerouslyInsertComponents.${insertedComponents} must be a valid JSONX JSON Object: ${e.toString()}` ) ); } } ); } if (jsonx.__functionProps) { if (typeof jsonx.__functionProps !== "object") { errors.push(TypeError("[0012] jsonx.__functionProps must be an object")); } else { Object.keys(jsonx.__functionProps).forEach(fProp => { if ( jsonx.__functionProps && jsonx.__functionProps[fProp] && (typeof jsonx.__functionProps[fProp] !== "string" || jsonx.__functionProps[fProp].indexOf("func:") === -1) ) { errors.push( ReferenceError( `[0013] jsonx.__functionProps.${fProp} must reference a function (i.e. func:this.props.logoutUser())` ) ); } }); } } if ( jsonx.__windowComponentProps && (typeof jsonx.__windowComponentProps !== "object" || Array.isArray(jsonx.__windowComponentProps)) ) { errors.push( TypeError("[0013] jsonx.__windowComponentProps must be an object") ); } if (jsonx.__windowComponents) { if (typeof jsonx.__windowComponents !== "object") { errors.push( TypeError("[0014] jsonx.__windowComponents must be an object") ); } Object.keys(jsonx.__windowComponents).forEach(cProp => { if ( typeof jsonx.__windowComponents[cProp] !== "string" || jsonx.__windowComponents[cProp].indexOf("func:") === -1 ) { errors.push( ReferenceError( `[0015] jsonx.__windowComponents.${cProp} must reference a window element on window.__jsonx_custom_elements (i.e. func:window.__jsonx_custom_elements.bootstrapModal)` ) ); } }); } if ( typeof jsonx.comparisonorprops !== "undefined" && typeof jsonx.comparisonorprops !== "boolean" ) { errors.push(TypeError("[0016] jsonx.comparisonorprops must be boolean")); } if (jsonx.comparisonprops) { if (!Array.isArray(jsonx.comparisonprops)) { errors.push( TypeError( "[0017] jsonx.comparisonprops must be an array or comparisons" ) ); } else { jsonx.comparisonprops.forEach(c => { if (typeof c !== "object") { errors.push( TypeError( "[0018] jsonx.comparisonprops must be an array or comparisons objects" ) ); } else if (typeof c.left === "undefined") { errors.push( TypeError( "[0019] jsonx.comparisonprops must be have a left comparison value" ) ); } }); } } if ( typeof jsonx.passprops !== "undefined" && typeof jsonx.passprops !== "boolean" ) { errors.push(TypeError("[0020] jsonx.passprops must be boolean")); } const invalidKeys = Object.keys(jsonx).filter( key => validKeys.indexOf(key) === -1 ); if (errors.length) { if (returnAllErrors) return errors; throw errors[0]; } return invalidKeys.length ? `Warning: Invalid Keys [${invalidKeys.join()}]` : true; } /** * validates simple JSONX Syntax {[component]:{props,children}} * @param {Object} simpleJSONX - Any valid simple JSONX Syntax * @return {Boolean} returns true if simpleJSONX is valid */ export function validSimpleJSONXSyntax(simpleJSONX: any = {}) { if (Object.keys(simpleJSONX).length !== 1 && !simpleJSONX.component) { return false; } else { const componentName = Object.keys(simpleJSONX)[0]; return Object.keys(simpleJSONX).length === 1 && !simpleJSONX[componentName].component && (typeof simpleJSONX[componentName] === "object" || typeof simpleJSONX[componentName] === "string") ? true : false; } } /** * Transforms SimpleJSONX to Valid JSONX JSON {[component]:{props,children}} => {component,props,children} * @param {Object} simpleJSONX JSON Object * @return {Object} - returns a valid JSONX JSON Object from a simple JSONX JSON Object */ export function simpleJSONXSyntax( simpleJSONX: defs.simpleJsonx = {} ): defs.jsonx { if(simpleJSONX.component) return simpleJSONX const component = Object.keys(simpleJSONX)[0]; try { const children = typeof simpleJSONX[component] ==='string' || Array.isArray(simpleJSONX[component]) ? simpleJSONX[component] : simpleJSONX[component] && simpleJSONX[component].children && Array.isArray(simpleJSONX[component].children) ? (simpleJSONX[component].children as defs.simpleJsonx[]).map(simpleJSONXSyntax) : simpleJSONX[component].children; const jsonxprops = typeof simpleJSONX[component] ==='object' ? simpleJSONX[component] : undefined; const jsonx = {component,...jsonxprops,children} return jsonx as defs.jsonx; // return Object.assign( // {}, // { // component // }, // simpleJSONX[component], // { // children: // simpleJSONX[component] && // simpleJSONX[component].children && // Array.isArray(simpleJSONX[component].children) // ? (simpleJSONX[component].children as defs.simpleJsonx[]).map( // simpleJSONXSyntax // ) // : simpleJSONX[component].children // } // ); } catch (e) { throw SyntaxError("Invalid Simple JSONX Syntax"); } } /** * Transforms Valid JSONX JSON to SimpleJSONX {component,props,children} => {[component]:{props,children}} * @param {Object} jsonx Valid JSONX JSON object * @return {Object} - returns a simple JSONX JSON Object from a valid JSONX JSON Object */ export function getSimplifiedJSONX(jsonx: defs.jsonx = {}) { try { if (!jsonx.component) return jsonx; //already simple const componentName = jsonx.component; jsonx.children = Array.isArray(jsonx.children) ? jsonx.children .filter(child => child) //remove empty children .map(getSimplifiedJSONX) : jsonx.children; delete jsonx.component; return { [componentName]: jsonx }; } catch (e) { throw e; } } /** * Fetches JSON from remote path * @param {String} path - fetch path url * @param {Object} options - fetch options * @return {Object} - returns fetched JSON data */ export async function fetchJSON(path: string = "", options = {}) { try { const response = await fetch(path, options); return await response.json(); } catch (e) { throw e; } } // export function Deprecated(): MethodDecorator { // return (target: Object, key: string | symbol, descriptor: PropertyDescriptor) => { // const original = descriptor.value; // descriptor.value = (...args: any) => { // console.warn(`Warning: ${String(key)} is deprecated`); // original(...args); // } // return descriptor; // } // }
the_stack
module entitas { "use strict" import Pool = entitas.Pool import Signal = entitas.utils.Signal import ISignal = entitas.utils.ISignal import IComponent = entitas.IComponent import EntityChanged = Entity.EntityChanged import EntityReleased = Entity.EntityReleased import IEntityChanged = Entity.IEntityChanged import IEntityReleased = Entity.IEntityReleased import ComponentReplaced = Entity.ComponentReplaced import IComponentReplaced = Entity.IComponentReplaced import EntityIsNotEnabledException = entitas.exceptions.EntityIsNotEnabledException import EntityIsAlreadyReleasedException = entitas.exceptions.EntityIsAlreadyReleasedException import EntityAlreadyHasComponentException = entitas.exceptions.EntityAlreadyHasComponentException import EntityDoesNotHaveComponentException = entitas.exceptions.EntityDoesNotHaveComponentException export module Entity { /** * Event EntityReleased * * All references to the entity have been released */ export interface EntityReleased {(e:Entity):void;} export interface IEntityReleased<T> extends ISignal<T> { dispatch(e:Entity):void } /** * Event EntityChanged * * The entity has been changed **/ export interface EntityChanged {(e:Entity, index:number, component:IComponent):void;} export interface IEntityChanged<T> extends ISignal<T> { dispatch(e:Entity, index:number, component:IComponent):void } /** * Event ComponentReplaced * * A component was replaced */ export interface ComponentReplaced {(e:Entity, index:number, component:IComponent, replacement:IComponent):void;} export interface IComponentReplaced<T> extends ISignal<T> { dispatch(e:Entity, index:number, component:IComponent, replacement:IComponent):void } } export class Entity { /** * @static * @type {number} */ public static instanceIndex:number = 0 /** * @static * @type {Array<Array<IComponent>>} */ public static alloc:Array<Array<IComponent>> = null /** * @static * @type {number} */ public static size:number = 0 /** * A unique sequential index number assigned to each entity at creation * @type {number} * @name entitas.Entity#creationIndex */ public get creationIndex():number {return this._creationIndex;} /** * Subscribe to Entity Released Event * @type {entitas.ISignal} */ public onEntityReleased:IEntityReleased<EntityReleased> = null /** * Subscribe to Component Added Event * @type {entitas.ISignal} */ public onComponentAdded:IEntityChanged<EntityChanged> = null /** * Subscribe to Component Removed Event * @type {entitas.ISignal} */ public onComponentRemoved:IEntityChanged<EntityChanged> = null /** * Subscribe to Component Replaced Event * @type {entitas.ISignal} */ public onComponentReplaced:Entity.IComponentReplaced<ComponentReplaced> = null /** * Entity name * @type {string} */ public name:string = '' /** * Entity Id * @type {string} */ public id:string = '' /** * Instance index * @type {number} */ public instanceIndex:number = 0 public _creationIndex:number = 0 public _isEnabled:boolean = true public _components:Array<IComponent> = null public _componentsCache = null public _componentIndicesCache:number[] = null public _toStringCache:string = '' public _refCount:number = 0 private _pool:Pool = null private _componentsEnum:{} = null /** * The basic game object. Everything is an entity with components that * are added / removed as needed. * * @param {Object} componentsEnum * @param {number} totalComponents * @constructor */ constructor(componentsEnum, totalComponents:number=16) { this.onEntityReleased = new Signal<EntityReleased>(this) this.onComponentAdded = new Signal<EntityChanged>(this) this.onComponentRemoved = new Signal<EntityChanged>(this) this.onComponentReplaced = new Signal<ComponentReplaced>(this) this._componentsEnum = componentsEnum this._pool = entitas.Pool.instance this._components = this.initialize(totalComponents) } public static initialize(totalComponents:number, options) { Entity.size = options.entities || 100 } /** * allocate entity pool * * @param count number of components * @param size max number of entities */ public static dim(count:number, size:number): void { Entity.alloc = new Array(size) for (let e=0; e<size; e++) { Entity.alloc[e] = new Array(count) for (let k=0; k<count; k++) { Entity.alloc[e][k] = null } } } /** * Initialize * allocate the entity pool. * * @param {number} totalComponents * @returns {Array<entitas.IComponent>} */ public initialize(totalComponents:number):Array<IComponent> { let mem const size = Entity.size if (Entity.alloc == null) Entity.dim(totalComponents, size) const alloc = Entity.alloc this.instanceIndex = Entity.instanceIndex++ if (mem = alloc[this.instanceIndex]) return mem console.log('Insufficient memory allocation at ', this.instanceIndex, '. Allocating ', size, ' entities.') for (let i=this.instanceIndex, l=i+size; i<l; i++) { alloc[i] = new Array(totalComponents) for (let k=0; k<totalComponents; k++) { alloc[i][k] = null } } mem = alloc[this.instanceIndex] return mem } /** * AddComponent * * @param {number} index * @param {entitas.IComponent} component * @returns {entitas.Entity} */ public addComponent(index:number, component:IComponent):Entity { if (!this._isEnabled) { throw new EntityIsNotEnabledException("Cannot add component!") } if (this.hasComponent(index)) { const errorMsg = "Cannot add component at index " + index + " to " + this throw new EntityAlreadyHasComponentException(errorMsg, index) } this._components[index] = component this._componentsCache = null this._componentIndicesCache = null this._toStringCache = null const onComponentAdded:any = this.onComponentAdded if (onComponentAdded.active) onComponentAdded.dispatch(this, index, component) return this } /** * RemoveComponent * * @param {number} index * @returns {entitas.Entity} */ public removeComponent(index:number):Entity { if (!this._isEnabled) { throw new EntityIsNotEnabledException("Cannot remove component!") } if (!this.hasComponent(index)) { const errorMsg = "Cannot remove component at index " + index + " from " + this throw new EntityDoesNotHaveComponentException(errorMsg, index) } this._replaceComponent(index, null) return this } /** * ReplaceComponent * * @param {number} index * @param {entitas.IComponent} component * @returns {entitas.Entity} */ public replaceComponent(index:number, component:IComponent):Entity { if (!this._isEnabled) { throw new EntityIsNotEnabledException("Cannot replace component!") } if (this.hasComponent(index)) { this._replaceComponent(index, component) } else if (component != null) { this.addComponent(index, component) } return this } protected _replaceComponent(index:number, replacement:IComponent) { const components = this._components const previousComponent = components[index] if (previousComponent === replacement) { let onComponentReplaced:any = this.onComponentReplaced if (onComponentReplaced.active) onComponentReplaced.dispatch(this, index, previousComponent, replacement) } else { components[index] = replacement this._componentsCache = null if (replacement == null) { //delete components[index] components[index] = null this._componentIndicesCache = null this._toStringCache = null const onComponentRemoved:any = this.onComponentRemoved if (onComponentRemoved.active) onComponentRemoved.dispatch(this, index, previousComponent) } else { const onComponentReplaced:any = this.onComponentReplaced if (onComponentReplaced.active) onComponentReplaced.dispatch(this, index, previousComponent, replacement) } } } /** * GetComponent * * @param {number} index * @param {entitas.IComponent} component */ public getComponent(index:number):IComponent { if (!this.hasComponent(index)) { const errorMsg = "Cannot get component at index " + index + " from " + this throw new EntityDoesNotHaveComponentException(errorMsg, index) } return this._components[index] } /** * GetComponents * * @returns {Array<entitas.IComponent>} */ public getComponents():IComponent[] { if (this._componentsCache == null) { const components = [] const _components = this._components for (let i = 0, j = 0, componentsLength = _components.length; i < componentsLength; i++) { const component = _components[i] if (component != null) { components[j++] = component } } this._componentsCache = components } return this._componentsCache } /** * GetComponentIndices * * @returns {Array<number>} */ public getComponentIndices():number[] { if (this._componentIndicesCache == null) { const indices = [] const _components = this._components for (let i = 0, j = 0, componentsLength = _components.length; i < componentsLength; i++) { if (_components[i] != null) { indices[j++] = i } } this._componentIndicesCache = indices } return this._componentIndicesCache } /** * HasComponent * * @param {number} index * @returns {boolean} */ public hasComponent(index:number):boolean { return this._components[index] != null } /** * HasComponents * * @param {Array<number>} indices * @returns {boolean} */ public hasComponents(indices:number[]):boolean { const _components = this._components for (let i = 0, indicesLength = indices.length; i < indicesLength; i++) { if (_components[indices[i]] == null) { return false } } return true } /** * HasAnyComponent * * @param {Array<number>} indices * @returns {boolean} */ public hasAnyComponent(indices:number[]):boolean { const _components = this._components for (let i = 0, indicesLength = indices.length; i < indicesLength; i++) { if (_components[indices[i]] != null) { return true } } return false } /** * RemoveAllComponents * */ public removeAllComponents() { this._toStringCache = null const _components = this._components for (let i = 0, componentsLength = _components.length; i < componentsLength; i++) { if (_components[i] != null) { this._replaceComponent(i, null) } } } /** * Destroy * */ public destroy() { this.removeAllComponents() this.onComponentAdded.clear() this.onComponentReplaced.clear() this.onComponentRemoved.clear() this._isEnabled = false } /** * ToString * * @returns {string} */ public toString() { if (this._toStringCache == null) { const sb = [] const seperator = ", " const components = this.getComponents() const lastSeperator = components.length - 1 for (let i = 0, j=0, componentsLength = components.length; i < componentsLength; i++) { sb[j++] = components[i].constructor['name'].replace('Component', '') || i+'' if (i < lastSeperator) { sb[j++] = seperator } } this._toStringCache = sb.join('') } return this._toStringCache } /** * AddRef * * @returns {entitas.Entity} */ public addRef():Entity { this._refCount += 1 return this } /** * Release * */ public release() { this._refCount -= 1 if (this._refCount === 0) { let onEntityReleased:any = this.onEntityReleased if (onEntityReleased.active) onEntityReleased.dispatch(this) } else if (this._refCount < 0) { throw new EntityIsAlreadyReleasedException() } } } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview The common bootstrap code for pages that show a map, a list of aircraft and aircraft details. */ namespace VRS { /** * The settings that need to be passed to a new instance of BootstrapMap. */ export interface BootstrapMap_Settings extends Bootstrap_Settings { /** * Optional settings to send to IMap.open() */ mapSettings?: IMapOpenOptions; /** * True if we don't want the page title to show the count of aircraft. */ suppressTitleUpdate?: boolean; /** * Where to draw the settings button on the map. */ settingsPosition?: MapPositionEnum; /** * True if options are to be shown in a separate page, false if they're to be shown in a dialog. Default false. */ showOptionsInPage?: boolean; /** * The base URL for reports. */ reportUrl?: string; } /** * The page settings for the BootstrapMap. */ export interface PageSettings_Map extends PageSettings_Base { /** * Filled by Bootstrap with the object that automatically selects aircraft for us. */ aircraftAutoSelect?: AircraftAutoSelect; /** * The jQuery element where the aircraft default panel will be drawn. Defaults to null. */ aircraftDetailJQ?: JQuery; /** * Filled by Bootstrap with the page panel that will hold the aircraft detail on the mobile site. */ aircraftDetailPagePanelJQ?: JQuery; /** * Filled by Bootstrap with the aircraft list that the page is using. */ aircraftList?: AircraftList; /** * Filled by Bootstrap with the aircraft list fetcher that the page is using. */ aircraftListFetcher?: AircraftListFetcher; /** * Filled by Bootstrap with the object that can filter the aircraft list. */ aircraftListFilter?: AircraftListFilter; /** * The jQuery element where the aircraft list will be drawn. Defaults to null. */ aircraftListJQ?: JQuery; /** * Filled by Bootstrap with the page panel that will hold the aircraft list on the mobile site. */ aircraftListPagePanelJQ?: JQuery; /** * Filled by Bootstrap with the aircraft list sorter that the site will use. */ aircraftListSorter?: AircraftListSorter; /** * Filled by Bootstrap with the object that can draw aircraft onto the map. */ aircraftPlotter?: AircraftPlotter; /** * Filled by Bootstrap with the object that carries aircraft plotter options around. */ aircraftPlotterOptions?: AircraftPlotterOptions; /** * Filled by Bootstrap with the object that can handle callbacks of a selected aircraft's details. */ audio?: AudioWrapper; /** * Filled by Bootstrap with the element used as the info window shown against selected aircraft. */ infoWindowJQ?: JQuery; /** * Filled by Bootstrap with a direct reference to the infoWindow plugin. */ infoWindowPlugin?: AircraftInfoWindowPlugin; /** * Filled by Bootstrap with the element created for the next page button. */ mapNextPageButton?: JQuery; /** * A direct reference to the map plugin attached to the map jQuery object. Filled in by the bootstrapper, will be null if there is no map. */ mapPlugin?: IMap; /** * Filled by Bootstrap with the page panel used to hold the options page for the mobile site. */ optionsPagePanelJQ?: JQuery; /** * Filled by Bootstrap with a set of option pages that hold the configurable items for the site. */ pages?: OptionPage[]; /** * The jQuery element while will act as the parent for pages. If not supplied then the page manager is not used. */ pagesJQ?: JQuery; /** * Filled by Bootstrap with the object that can manage polar plots for us. */ polarPlotter: PolarPlotter; /** * True if the user should be shown the audio settings. Defaults to true. */ showAudioSetting?: boolean; /** * True if the user can toggle auto-select from the menu. Defaults to true. */ showAutoSelectToggle?: boolean; /** * True if the user is to be shown the option to jump to the current location. */ showGotoCurrentLocation?: boolean; /** * True if the user is to be shown the option to jump to the selected aircraft's location. */ showGotoSelectedAircraft?: boolean; /** * True if the user should be allowed to switch languages. Defaults to true. */ showLanguageSetting?: boolean; /** * True if the user should be shown the moving map button. Defaults to true. */ showMovingMapSetting?: boolean; /** * True if the user should be shown the settings map button. Defaults to true. */ showOptionsSetting?: boolean; /** * True if the user should be shown the pause button. Defaults to true. */ showPauseSetting?: boolean; /** * True if the user should be shown the option to toggle range circles. Defaults to true. */ showRangeCircleSetting?: boolean; /** * True if the user can change receivers from the menu. Defaults to true. */ showReceiversShortcut?: boolean; /** * True if the user should be shown the links to standard reports. Defaults to true. */ showReportLinks?: boolean; /** * Filled by Bootstrap with the element holding the timeout message box plugin. */ timeoutMessageBox?: JQuery; /** * Filled by Bootstrap with the page's title updater. */ titleUpdater?: TitleUpdater; } /** * The object that deals with creating all of the objects necessary for the map pages and wiring them all together. */ export class BootstrapMap extends Bootstrap { protected _Settings: BootstrapMap_Settings; constructor(settings: BootstrapMap_Settings) { settings = $.extend({ dispatcherName: 'VRS.BootstrapMap', suppressTitleUpdate: false, settingsPosition: VRS.MapPosition.TopLeft, settingsMenuAlignment: VRS.Alignment.Left, showOptionsInPage: false }, settings); super(settings); } /** * Builds the page. */ initialise(pageSettings: PageSettings_Map) { pageSettings = $.extend({ splittersJQ: null, pagesJQ: null, mapJQ: null, mapSettings: {}, showSettingsButton: true, showLayersMenu: true, settingsMenu: null, aircraftDetailJQ: null, aircraftListJQ: null, showOptionsSetting: true, showLanguageSetting: true, showLayoutSetting: true, showReceiversShortcut: true, showMovingMapSetting: true, showPauseSetting: true, showAudioSetting: true, showRangeCircleSetting: true, showReportLinks: true, showAutoSelectToggle: true, showGotoCurrentLocation: true, showGotoSelectedAircraft: true, showPolarPlotterSetting: true }, pageSettings); // Common startup stuff this.doStartInitialise(pageSettings, () => { // Page title if(!this._Settings.suppressTitleUpdate) { document.title = VRS.$$.VirtualRadar; } // Load the map. If the user has disabled the map then jump straight to the "map loaded" callback. if(!pageSettings.mapJQ) { this.mapLoaded(pageSettings); } else { pageSettings.mapSettings = $.extend(pageSettings.mapSettings, { useStateOnOpen: true, autoSaveState: true, useServerDefaults: true, loadMarkerWithLabel: true, loadMarkerCluster: true, controlStyle: VRS.MapControlStyle.DropdownMenu, afterOpen: () => { this.raiseMapInitialising(pageSettings); this.mapLoaded(pageSettings); this.raiseMapInitialised(pageSettings); } }, this._Settings.mapSettings || {}); this.raiseMapSettingsInitialised(pageSettings); pageSettings.mapJQ.vrsMap(VRS.jQueryUIHelper.getMapOptions(pageSettings.mapSettings)); } }); } /** * Called once the map has finished loading. */ private mapLoaded(pageSettings: PageSettings_Map) { // Keep a reference to the map pageSettings.mapPlugin = pageSettings.mapJQ ? VRS.jQueryUIHelper.getMapPlugin(pageSettings.mapJQ) : null; if(pageSettings.mapPlugin && !pageSettings.mapPlugin.isOpen()) { pageSettings.mapPlugin = null; } this.raiseMapLoaded(pageSettings); // Initialise the map layers manager if(VRS.mapLayerManager) { VRS.mapLayerManager.registerMap(pageSettings.mapPlugin); } // Set up the current location if(VRS.currentLocation) { if(pageSettings.mapJQ) { VRS.currentLocation.setMapForApproximateLocation(pageSettings.mapJQ); } VRS.currentLocation.loadAndApplyState(); } // Add the settings button var settingsButton = this.createMapSettingsControl(pageSettings); if(pageSettings.mapPlugin) { if(settingsButton) { pageSettings.mapPlugin.addControl(pageSettings.menuJQ, this._Settings.settingsPosition); } } else if(pageSettings.mapJQ) { pageSettings.mapJQ.children().first().prepend(settingsButton); } // Create the aircraft list pageSettings.aircraftList = new VRS.AircraftList(); // Create the object that fetches the aircraft list. pageSettings.aircraftListFetcher = new VRS.AircraftListFetcher({ aircraftList: pageSettings.aircraftList, currentLocation: VRS.currentLocation, mapJQ: pageSettings.mapJQ, fetchFsxList: VRS.globalOptions.isFlightSim }); pageSettings.aircraftListFetcher.loadAndApplyState(); // Create the polar plotter if(VRS.globalOptions.polarPlotEnabled && pageSettings.mapPlugin && pageSettings.aircraftListFetcher) { pageSettings.polarPlotter = new VRS.PolarPlotter({ map: pageSettings.mapPlugin, aircraftListFetcher: pageSettings.aircraftListFetcher, unitDisplayPreferences: pageSettings.unitDisplayPreferences }); pageSettings.polarPlotter.startAutoRefresh(); } // Create the timeout message box if(VRS.jQueryUIHelper.getTimeoutMessageBox) { pageSettings.timeoutMessageBox = $('<div/>') .vrsTimeoutMessageBox({ aircraftListFetcher: pageSettings.aircraftListFetcher }) .appendTo('body'); } // Create the object that manages the page title changes if(!this._Settings.suppressTitleUpdate) { pageSettings.titleUpdater = new VRS.TitleUpdater(); pageSettings.titleUpdater.showAircraftListCount(pageSettings.aircraftList); } // Create the object that automatically selects aircraft if(VRS.AircraftAutoSelect) { pageSettings.aircraftAutoSelect = new VRS.AircraftAutoSelect(pageSettings.aircraftList); pageSettings.aircraftAutoSelect.loadAndApplyState(); } // Create the object that can filter the aircraft list if(VRS.AircraftListFilter) { pageSettings.aircraftListFilter = new VRS.AircraftListFilter({ aircraftList: pageSettings.aircraftList, unitDisplayPreferences: pageSettings.unitDisplayPreferences }); pageSettings.aircraftListFilter.loadAndApplyState(); } // Optionally preselect to an ICAO off the query string parameters if(purl && pageSettings.aircraftAutoSelect) { var preselectIcao = $.url().param('icao'); if(preselectIcao !== null && preselectIcao !== undefined && preselectIcao.length === 6) { pageSettings.aircraftAutoSelect.setSelectAircraftByIcao(preselectIcao.toUpperCase()); pageSettings.aircraftAutoSelect.setAutoClearSelectAircraftByIcao(true); var filterToIcaoText = $.url().param('filter'); if(filterToIcaoText !== null && filterToIcaoText !== undefined && pageSettings.aircraftListFilter) { pageSettings.aircraftListFilter.removeAllFilters(); if(filterToIcaoText !== '0') { var filter = pageSettings.aircraftListFilter.addFilter(AircraftFilterProperty.Icao); filter.setValueCondition(new OneValueCondition(FilterCondition.Equals, false, preselectIcao)); pageSettings.aircraftListFilter.setEnabled(true); } } } } // Create the object that plots aircraft on the map if(pageSettings.mapPlugin && VRS.AircraftPlotter) { pageSettings.aircraftPlotterOptions = new VRS.AircraftPlotterOptions({ map: pageSettings.mapPlugin }); pageSettings.aircraftPlotterOptions.loadAndApplyState(); pageSettings.aircraftPlotter = new VRS.AircraftPlotter({ plotterOptions: pageSettings.aircraftPlotterOptions, aircraftList: pageSettings.aircraftList, map: pageSettings.mapJQ, unitDisplayPreferences: pageSettings.unitDisplayPreferences }); pageSettings.aircraftPlotter.refreshRangeCircles(); if(purl) { var initialMovingMapStatus = $.url().param('movingMap'); if(initialMovingMapStatus !== null && initialMovingMapStatus !== undefined) { pageSettings.aircraftPlotter.setMovingMap(initialMovingMapStatus !== '0'); } } } // Create the info window that gets shown against the selected aircraft. if(VRS.jQueryUIHelper.getAircraftInfoWindowPlugin && pageSettings.aircraftPlotterOptions) { pageSettings.infoWindowJQ = $('<div/>') .vrsAircraftInfoWindow(VRS.jQueryUIHelper.getAircraftInfoWindowOptions({ aircraftList: pageSettings.aircraftList, aircraftPlotter: pageSettings.aircraftPlotter, unitDisplayPreferences: pageSettings.unitDisplayPreferences })); pageSettings.infoWindowPlugin = VRS.jQueryUIHelper.getAircraftInfoWindowPlugin(pageSettings.infoWindowJQ); } // Create the aircraft list sorter if(VRS.AircraftListSorter) { pageSettings.aircraftListSorter = new VRS.AircraftListSorter(); pageSettings.aircraftListSorter.loadAndApplyState(); } // Create the aircraft detail panel if(pageSettings.aircraftDetailJQ) { this.initialiseAircraftDetailPanel(pageSettings); this.raiseAircraftDetailPanelInitialised(pageSettings); } // Create the aircraft list panel if(pageSettings.aircraftListJQ) { this.initialiseAircraftListPanel(pageSettings); this.raiseAircraftListPanelInitialised(pageSettings); } // Create the object that calls out selected aircraft details if(VRS.AudioWrapper) { pageSettings.audio = new VRS.AudioWrapper(); pageSettings.audio.loadAndApplyState(); pageSettings.audio.annouceSelectedAircraftOnList(pageSettings.aircraftList); } // Build up the splitter layouts (desktop) or pages (mobile) if(pageSettings.pagesJQ) this.initialisePageManager(pageSettings); if(pageSettings.splittersJQ) { if(VRS.globalOptions.isFlightSim) this.initialiseFsxLayout(pageSettings); else this.initialisePageLayouts(pageSettings); } // Build up the menu options for the settings button if(pageSettings.settingsMenu) { pageSettings.settingsMenu.hookBeforeAddingFixedMenuItems(function(unused, menuItems) { this.buildSettingsMenu(pageSettings, menuItems); }, this); } // All done this.doEndInitialise(pageSettings); // Start the first fetch and trigger the display of any initial polar plots pageSettings.aircraftListFetcher.setPaused(false); if(pageSettings.polarPlotter) { pageSettings.polarPlotter.loadAndApplyState(); } } //endregion /** * Populates the settings menu. * @param {*} pageSettings * @param {VRS.MenuItem[]} menuItems */ private buildSettingsMenu(pageSettings, menuItems) { if(pageSettings.showOptionsSetting) { menuItems.push(this.createOptionsMenuEntry(pageSettings)); } if(pageSettings.showLanguageSetting) { menuItems.push(this.createLocaleMenuEntry(pageSettings)); } if(pageSettings.showReceiversShortcut && VRS.globalOptions.aircraftListUserCanChangeFeeds && pageSettings.aircraftListFetcher.getFeeds().length > 1) { menuItems.push(this.createReceiversMenuEntry(pageSettings)); } if(pageSettings.showPolarPlotterSetting && pageSettings.polarPlotter && pageSettings.polarPlotter.getPolarPlotterFeeds().length) { menuItems.push(this.createPolarPlotterMenuEntry(pageSettings)); } menuItems.push(this.createShortcutsMenuEntry(pageSettings)); // Didn't have enough time to update the documentation for the website help // Will come back to this in a future update // menuItems.push(base.createHelpMenuEntry('WebSite/DesktopPage.aspx')); menuItems.push(null); if(pageSettings.showAudioSetting && pageSettings.audio) { menuItems.push(this.createAudioMenuEntry(pageSettings)); pageSettings.settingsMenu.getTopLevelMenuItems().push(null); } if(pageSettings.showLayoutSetting && pageSettings.layoutMenuItem) { menuItems.push(pageSettings.layoutMenuItem); pageSettings.settingsMenu.getTopLevelMenuItems().push(null); } if(pageSettings.showReportLinks && (!VRS.serverConfig || VRS.serverConfig.reportsEnabled())) { menuItems.push(this.createReportsMenuEntry(pageSettings)); } var mapWrapper = VRS.jQueryUIHelper.getMapPlugin(pageSettings.mapJQ); var layerMenuItem = this.createLayersMenuEntry(pageSettings, mapWrapper, true); if(layerMenuItem) { menuItems.push(null); menuItems.push(layerMenuItem); } } /** * Creates a menu entry for the options screen. */ private createOptionsMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'options', labelKey: 'Options', vrsIcon: 'equalizer', clickCallback: () => { if(this._Settings.showOptionsInPage) { VRS.pageManager.show(VRS.MobilePageName.Options); } else { this.buildOptionPanelPages(pageSettings); $('<div/>') .appendTo($('body')) .vrsOptionDialog(VRS.jQueryUIHelper.getOptionDialogOptions({ pages: pageSettings.pages, autoRemove: true })); } } }); } /** * Creates a menu entry for the shortcuts. */ private createShortcutsMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var menuEntry = new VRS.MenuItem({ name: 'shortcuts', labelKey: 'Shortcuts' }); var menuItems = menuEntry.subItems; if(pageSettings.mapPlugin) { if(pageSettings.showMovingMapSetting) menuItems.push(this.createMovingMapMenuEntry(pageSettings)); if(pageSettings.showRangeCircleSetting && VRS.globalOptions.aircraftMarkerAllowRangeCircles) menuItems.push(this.createRangeCirclesMenuEntry(pageSettings)); } if(pageSettings.showPauseSetting && pageSettings.aircraftListFetcher) menuItems.push(this.createPauseMenuEntry(pageSettings)); if(pageSettings.showGotoCurrentLocation && pageSettings.mapPlugin && VRS.currentLocation) menuItems.push(this.createGotoCurrentLocationMenuEntry(pageSettings)); menuItems.push(null); if(pageSettings.showGotoSelectedAircraft && pageSettings.mapPlugin) menuItems.push(this.createGotoSelectedAircraftMenuEntry(pageSettings)); if(pageSettings.showAutoSelectToggle) menuItems.push(this.createAutoSelectMenuEntry(pageSettings)); return menuEntry; } /** * Creates a menu entry that lets the user change receiver. */ private createReceiversMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var result = new VRS.MenuItem({ name: 'receivers', labelKey: 'Receiver' }); var feeds = pageSettings.aircraftListFetcher.getSortedFeeds(true); var currentFeed = pageSettings.aircraftListFetcher.getActualFeedId(); $.each(feeds, function(idx, feed) { result.subItems.push(new VRS.MenuItem({ name: 'receiver-' + idx, labelKey: function() { return feed.name; }, disabled: function() { return feed.id === currentFeed; }, checked: function() { return feed.id === currentFeed; }, clickCallback: function() { pageSettings.aircraftListFetcher.setRequestFeedId(feed.id); pageSettings.aircraftListFetcher.saveState(); } })); }); return result; } /** * Creates a menu entry for displaying the polar plotter. */ private createPolarPlotterMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var result = new VRS.MenuItem({ name: 'polarPlotter', labelKey: 'ReceiverRange' }); var feeds = pageSettings.polarPlotter.getSortedPolarPlotterFeeds(); var countFeeds = feeds.length; $.each(feeds, function(idx, feed) { var subMenu = null; if(countFeeds === 1) { subMenu = result; } else { subMenu = new VRS.MenuItem({ name: 'polarPlotter-' + idx + '-' + feed.id, labelKey: function() { return feed.name; } }); result.subItems.push(subMenu); } var onDisplay = []; $.each(pageSettings.polarPlotter.getAltitudeRangeConfigs(), function(altIdx, altitudeRange) { if(altIdx === 1) { subMenu.subItems.push(null); } var isChecked = pageSettings.polarPlotter.isOnDisplay(feed.id, altitudeRange.low, altitudeRange.high); subMenu.subItems.push(new VRS.MenuItem({ name: subMenu.name + '-' + altIdx, labelKey: function() { return pageSettings.polarPlotter.getSliceRangeDescription(altitudeRange.low, altitudeRange.high); }, checked: function() { return isChecked; }, clickCallback: function() { isChecked = pageSettings.polarPlotter.fetchAndToggleByIdentifiers([{ feedId: feed.id, lowAlt: altitudeRange.low, highAlt: altitudeRange.high }]); }, noAutoClose: true })); }); }); if(countFeeds > 1) { result.subItems.push(null); result.subItems.push(new VRS.MenuItem({ name: 'polarPlotter-masterRemoveAll', labelKey: 'RemoveAll', clickCallback: function() { pageSettings.polarPlotter.removeAllSlicesForAllFeeds(); } })); } return result; } /** * Creates a menu entry to toggle the moving map. */ private createMovingMapMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'movingMap', labelKey: 'MovingMap', checked: function() { return pageSettings.aircraftPlotter.getMovingMap(); }, clickCallback: function() { pageSettings.aircraftPlotter.setMovingMap(!pageSettings.aircraftPlotter.getMovingMap()); }, noAutoClose: true }); } /** * Creates a menu entry to toggle range circles. */ private createRangeCirclesMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'rangeCircles', labelKey: 'RangeCircles', checked: function() { return pageSettings.aircraftPlotterOptions.getShowRangeCircles(); }, clickCallback: function() { pageSettings.aircraftPlotterOptions.setShowRangeCircles(!pageSettings.aircraftPlotterOptions.getShowRangeCircles()); pageSettings.aircraftPlotterOptions.saveState(); }, noAutoClose: true }); } /** * Creates a menu entry to toggle fetching of the aircraft list. */ private createPauseMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'pause', labelKey: function() { return pageSettings.aircraftListFetcher.getPaused() ? VRS.$$.Resume : VRS.$$.Pause; }, vrsIcon: function() { return pageSettings.aircraftListFetcher.getPaused() ? 'play' : 'pause'; }, clickCallback: function() { pageSettings.aircraftListFetcher.setPaused(!pageSettings.aircraftListFetcher.getPaused()); }, noAutoClose: true }); } /** * Creates a menu entry that moves the map to the current location. */ private createGotoCurrentLocationMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'gotoCurrentLocation', labelKey: 'GotoCurrentLocation', disabled: function() { return VRS.currentLocation.getMapIsSupplyingLocation(); }, clickCallback: function() { pageSettings.mapPlugin.panTo(VRS.currentLocation.getCurrentLocation()); } }); } /** * Creates a menu entry that moves the map to the currently selected aircraft. */ private createGotoSelectedAircraftMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var selectedAircraft = pageSettings.aircraftList.getSelectedAircraft(); return new VRS.MenuItem({ name: 'gotoSelectedAircraft', labelKey: 'GotoSelectedAircraft', disabled: function() { return !selectedAircraft; }, clickCallback: function() { if(selectedAircraft) { pageSettings.mapPlugin.panTo(selectedAircraft.getPosition()); } } }); } /** * Creates a menu entry to toggle the auto-select setting. */ private createAutoSelectMenuEntry(pageSettings: PageSettings_Map) : MenuItem { return new VRS.MenuItem({ name: 'autoSelectToggle', labelKey: function () { return pageSettings.aircraftAutoSelect.getEnabled() ? VRS.$$.DisableAutoSelect : VRS.$$.EnableAutoSelect; }, clickCallback: function() { pageSettings.aircraftAutoSelect.setEnabled(!pageSettings.aircraftAutoSelect.getEnabled()); } }); } /** * Creates a set of menu entries to control audio. */ private createAudioMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var audioMenuItem = new VRS.MenuItem({ name: 'audio', labelKey: 'PaneAudio', vrsIcon: 'volume-high', suppress: function() { return !pageSettings.audio.canPlayAudio(true); }, }); audioMenuItem.subItems.push(new VRS.MenuItem({ name: 'audio-mute', labelKey: function() { return pageSettings.audio.getMuted() ? VRS.$$.MuteOff : VRS.$$.MuteOn; }, vrsIcon: function() { return pageSettings.audio.getMuted() ? 'volume-medium' : 'volume-mute'; }, clickCallback: function() { pageSettings.audio.setMuted(!pageSettings.audio.getMuted()); } })); audioMenuItem.subItems.push(new VRS.MenuItem({ name: 'audio-volume', labelKey: 'Volume', vrsIcon: 'volume-low', showSlider: true, sliderMinimum: 0, sliderMaximum: 100, sliderInitialValue: pageSettings.audio.getVolume() * 100, sliderDefaultValue: 100, sliderCallback: (value: number) => pageSettings.audio.setVolume(value / 100) })); return audioMenuItem; } /** * Creates a set of menu entries for the reports. */ private createReportsMenuEntry(pageSettings: PageSettings_Map) : MenuItem { var selectedAircraft; var reportMenuItem = new VRS.MenuItem({ name: 'report', labelKey: 'Reports', vrsIcon: 'print', noAutoClose: true, clickCallback: function() { selectedAircraft = pageSettings.aircraftList ? pageSettings.aircraftList.getSelectedAircraft() : null; } }); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-freeform', labelKey: 'ReportFreeForm', clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl), VRS.browserHelper.getVrsPageTarget('vrsReport') ); } })); reportMenuItem.subItems.push(null); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-today', labelKey: 'ReportTodaysFlights', clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl, { 'date-L': 0, 'date-U': 0, 'sort1': VRS.ReportSortColumn.Date, 'sortAsc1': 1, 'sort2': 'none' }), VRS.browserHelper.getVrsPageTarget('vrsReportToday'))} })); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-yesterday', labelKey: 'ReportYesterdaysFlights', clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl, { 'date-L': -1, 'date-U': -1, 'sort1': VRS.ReportSortColumn.Date, 'sortAsc1': 1, 'sort2': 'none' }), VRS.browserHelper.getVrsPageTarget('vrsReportYesterday'))} })); if(pageSettings.aircraftList) { reportMenuItem.subItems.push(null); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-registration', labelKey: function() { return selectedAircraft && selectedAircraft.registration.val ? VRS.stringUtility.format(VRS.$$.ReportRegistrationValid, selectedAircraft.formatRegistration()) : VRS.$$.ReportRegistrationInvalid; }, disabled: function() { return !selectedAircraft || !selectedAircraft.registration.val; }, clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl, { 'reg-Q': selectedAircraft.registration.val, // this needs to be the first parameter 'sort1': VRS.ReportSortColumn.Date, 'sortAsc1': 0, 'sort2': 'none' }), VRS.browserHelper.getVrsPageTarget('vrsReportRegistration'))} })); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-icao', labelKey: function() { return selectedAircraft && selectedAircraft.icao.val ? VRS.stringUtility.format(VRS.$$.ReportIcaoValid, selectedAircraft.formatIcao()) : VRS.$$.ReportIcaoInvalid; }, disabled: function() { return !selectedAircraft || !selectedAircraft.icao.val; }, clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl, { 'icao-Q': selectedAircraft.icao.val, 'sort1': VRS.ReportSortColumn.Date, 'sortAsc1': 0, 'sort2': 'none' }), VRS.browserHelper.getVrsPageTarget('vrsReportIcao'))} })); reportMenuItem.subItems.push(new VRS.MenuItem({ name: 'report-callsign', labelKey: function() { return selectedAircraft && selectedAircraft.callsign.val ? VRS.stringUtility.format(VRS.$$.ReportCallsignValid, selectedAircraft.formatCallsign(false)) : VRS.$$.ReportCallsignInvalid; }, disabled: function() { return !selectedAircraft || !selectedAircraft.callsign.val; }, clickCallback: () => { window.open(VRS.browserHelper.formVrsPageUrl(this._Settings.reportUrl, { 'call-Q': selectedAircraft.callsign.val, 'sort1': VRS.ReportSortColumn.Date, 'sortAsc1': 0, 'sort2': VRS.ReportSortColumn.Callsign, 'sortAsc2': 1, 'callPerms':'1' }), VRS.browserHelper.getVrsPageTarget('vrsReportCallsign'))} })); } return reportMenuItem; } /** * Constructs the aircraft detail panel and attaches it to the appropriate element. */ private initialiseAircraftDetailPanel(pageSettings: PageSettings_Map) { pageSettings.aircraftDetailJQ.vrsAircraftDetail(VRS.jQueryUIHelper.getAircraftDetailOptions({ aircraftList: pageSettings.aircraftList, unitDisplayPreferences: pageSettings.unitDisplayPreferences, aircraftAutoSelect: pageSettings.aircraftAutoSelect, mapPlugin: pageSettings.mapPlugin, useSavedState: true, mirrorMapJQ: pageSettings.mapPlugin ? pageSettings.mapJQ : null, plotterOptions: pageSettings.aircraftPlotterOptions })); } /** * Constructs the aircraft list panel and attaches it to the appropriate element. */ private initialiseAircraftListPanel(pageSettings: PageSettings_Map) { var options: AircraftListPlugin_Options = { aircraftList: pageSettings.aircraftList, aircraftListFetcher: pageSettings.aircraftListFetcher, unitDisplayPreferences: pageSettings.unitDisplayPreferences, useSavedState: true, sorter: pageSettings.aircraftListSorter, useSorterSavedState: !!((<any>VRS).aircraftListSorter) // This should only be set if they have the ye olde settings from when AircraftListSorter was a singleton }; if(VRS.globalOptions.isFlightSim) { options.showHideAircraftNotOnMap = false; } pageSettings.aircraftListJQ.vrsAircraftList(VRS.jQueryUIHelper.getAircraftListOptions(options)); } /** * Constructs the options configuration pages. */ private buildOptionPanelPages(pageSettings: PageSettings_Map) { pageSettings.pages = []; var generalPage = new VRS.OptionPage({ name: 'vrsGeneralPage', titleKey: 'PageGeneral', displayOrder: 100 }); pageSettings.pages.push(generalPage); generalPage.addPane(pageSettings.aircraftListFetcher.createOptionPane(100)); if(VRS.currentLocation && pageSettings.mapPlugin) { generalPage.addPane(VRS.currentLocation.createOptionPane(200, pageSettings.mapJQ)); } generalPage.addPane(pageSettings.unitDisplayPreferences.createOptionPane(400)); if(pageSettings.audio) { generalPage.addPane(pageSettings.audio.createOptionPane(500)); } var mapPage = new VRS.OptionPage({ name: 'vrsMapPage', titleKey: 'PageMapShort', displayOrder: 200 }); if(pageSettings.aircraftAutoSelect) { mapPage.addPane(pageSettings.aircraftAutoSelect.createOptionPane(100)); } if(pageSettings.aircraftPlotterOptions) { if(VRS.currentLocation && VRS.globalOptions.aircraftMarkerAllowRangeCircles) { mapPage.addPane(pageSettings.aircraftPlotterOptions.createOptionPaneForRangeCircles(200)); } } if(pageSettings.polarPlotter) { mapPage.addPane(pageSettings.polarPlotter.createOptionPane(300)); } pageSettings.pages.push(mapPage); var aircraftDetail = pageSettings.aircraftDetailJQ ? VRS.jQueryUIHelper.getAircraftDetailPlugin(pageSettings.aircraftDetailJQ) : null; if(pageSettings.aircraftPlotterOptions || aircraftDetail) { var aircraftPage = new VRS.OptionPage({ name: 'vrsAircraftPage', titleKey: 'PageAircraft', displayOrder: 300 }); pageSettings.pages.push(aircraftPage); if(pageSettings.aircraftPlotterOptions) aircraftPage.addPane(pageSettings.aircraftPlotterOptions.createOptionPane(100)); if(aircraftDetail) aircraftPage.addPane(aircraftDetail.createOptionPane(200)); if(pageSettings.infoWindowPlugin) aircraftPage.addPane(pageSettings.infoWindowPlugin.createOptionPane(300)); } var aircraftList = pageSettings.aircraftListJQ ? VRS.jQueryUIHelper.getAircraftListPlugin(pageSettings.aircraftListJQ) : null; if(aircraftList) { pageSettings.pages.push( new VRS.OptionPage({ name: 'vrsAircraftListPage', titleKey: 'PageList', displayOrder: 400, panes: [ aircraftList.createOptionPane(100) ] }) ); } if(pageSettings.aircraftListFilter) { pageSettings.pages.push( new VRS.OptionPage({ name: 'vrsAircraftFilterPage', titleKey: 'Filters', displayOrder: 500, panes: [ pageSettings.aircraftListFilter.createOptionPane(100) ] }) ); } this.raiseOptionsPagesInitialised(pageSettings); } /** * Adds the layout for the Flight Simulator X page. */ private initialiseFsxLayout(pageSettings: PageSettings_Map) { VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A00', labelKey: 'Layout1', layout: [ pageSettings.mapJQ, { name: 'S1', vertical: true, savePane: 2, collapsePane: 2, maxPane: 2, max: '80%', startSizePane: 2, startSize: 475 }, pageSettings.aircraftListJQ ] })); this.endLayoutInitialisation(pageSettings); } /** * Adds the page layouts to the layout manager. */ private initialisePageLayouts(pageSettings: PageSettings_Map) { // Classic layout (map on left, detail above list on right) VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A00', labelKey: 'Layout1', layout: [ pageSettings.mapJQ, { name: 'S1', vertical: true, savePane: 2, collapsePane: 2, maxPane: 2, max: '80%', startSizePane: 2, startSize: 550 }, [ pageSettings.aircraftDetailJQ, { name: 'S2', vertical: false, fixedPane: 1, savePane: 1, collapsePane: 1 }, pageSettings.aircraftListJQ ] ] })); // Tall detail layout (map above list on left, detail on right) VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A01', labelKey: 'Layout2', layout: [ [ pageSettings.mapJQ, { name: 'S1', vertical: false, savePane: 2, startSizePane: 1, startSize: '50%', collapsePane: 2 }, pageSettings.aircraftListJQ ], { name: 'S2', vertical: true, savePane: 2, startSizePane: 2, startSize: 410, collapsePane: 2 }, pageSettings.aircraftDetailJQ ] })); // Tall detail layout (list above map on left, detail on right) VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A02', labelKey: 'Layout3', layout: [ [ pageSettings.aircraftListJQ, { name: 'S1', vertical: false, savePane: 1, startSizePane: 2, startSize: '50%', collapsePane: 1 }, pageSettings.mapJQ ], { name: 'S2', vertical: true, savePane: 2, startSizePane: 2, startSize: 410, collapsePane: 2 }, pageSettings.aircraftDetailJQ ] })); // Tall list layout (map above detail on left, list on right) VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A03', labelKey: 'Layout4', layout: [ [ pageSettings.mapJQ, { name: 'S1', vertical: false, fixedPane: 2, savePane: 2, collapsePane: 2, startSizePane: 1, startSize: '50%' }, pageSettings.aircraftDetailJQ ], { name: 'S2', vertical: true, fixedPane: 2, savePane: 2, startSizePane: 2, startSize: 550, collapsePane: 2 }, pageSettings.aircraftListJQ ] })); // Tall list layout (detail above map on left, list on right) VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A04', labelKey: 'Layout5', layout: [ [ pageSettings.aircraftDetailJQ, { name: 'S1', vertical: false, fixedPane: 1, savePane: 1, collapsePane: 1, startSizePane: 2, startSize: '50%' }, pageSettings.mapJQ ], { name: 'S2', vertical: true, fixedPane: 2, savePane: 2, startSizePane: 2, startSize: 550, collapsePane: 2 }, pageSettings.aircraftListJQ ] })); var mapButtonParent = null; var mapButtonContainer = $('<div />').addClass('mapButtonContainer'); var aircraftListPlugin = VRS.jQueryUIHelper.getAircraftListPlugin(pageSettings.aircraftListJQ); VRS.layoutManager.registerLayout(new VRS.Layout({ name: 'vrsLayout-A05', labelKey: 'Layout6', layout: [ pageSettings.aircraftListJQ, { name: 'S1', vertical: true, collapsePane: 2, savePane: 1, startSize: 550, fixedPane: 1, startSizePane: 1 }, pageSettings.aircraftDetailJQ ], onFocus: function() { if(pageSettings.aircraftPlotter) pageSettings.aircraftPlotter.suspend(true); if(pageSettings.mapJQ) { pageSettings.mapJQ.hide(); if(pageSettings.mapButton) { mapButtonParent = pageSettings.mapButton.parent(); pageSettings.mapButton.detach(); mapButtonContainer.append(pageSettings.mapButton); aircraftListPlugin.prependElement(mapButtonContainer); } } }, onBlur: function() { if(pageSettings.mapJQ) { if(pageSettings.mapButton) { mapButtonContainer.detach(); pageSettings.mapButton.detach(); mapButtonParent.append(pageSettings.mapButton); } pageSettings.mapJQ.show(); } if(pageSettings.aircraftPlotter) pageSettings.aircraftPlotter.suspend(false); } })); this.endLayoutInitialisation(pageSettings); this.createLayoutMenuEntry(pageSettings, [ 'Layout2', 'Layout4', 'Layout6' ]); } /** * Adds pages to the page manager. Only used by the mobile site. */ private initialisePageManager(pageSettings: PageSettings_Map) { VRS.pageManager.initialise(pageSettings.pagesJQ); if(pageSettings.mapJQ) { VRS.pageManager.addPage(new VRS.Page({ name: VRS.MobilePageName.Map, element: pageSettings.mapJQ, visibleCallback: function(isVisible) { if(pageSettings.aircraftPlotter) { pageSettings.aircraftPlotter.suspend(!isVisible); } if(pageSettings.infoWindowPlugin) { pageSettings.infoWindowPlugin.suspend(!isVisible); } }, afterVisibleCallback: function() { if(pageSettings.mapPlugin) { pageSettings.mapPlugin.refreshMap(); } if(pageSettings.infoWindowPlugin) { pageSettings.infoWindowPlugin.refreshDisplay(); } } })); pageSettings.mapNextPageButton = $('<div/>') .vrsMapNextPageButton(VRS.jQueryUIHelper.getMapNextPageButtonOptions({ nextPageName: VRS.MobilePageName.AircraftList, aircraftListFetcher: pageSettings.aircraftListFetcher, aircraftListFilter: pageSettings.aircraftListFilter })); if(pageSettings.mapPlugin) { pageSettings.mapPlugin.addControl(pageSettings.mapNextPageButton, VRS.MapPosition.TopRight); } else if(pageSettings.mapJQ) { pageSettings.mapJQ.children().first().append(pageSettings.mapNextPageButton); } } if(pageSettings.aircraftDetailJQ) { pageSettings.aircraftDetailPagePanelJQ = $('<div/>') .appendTo($('body')) .vrsPagePanel(VRS.jQueryUIHelper.getPagePanelOptions({ element: pageSettings.aircraftDetailJQ, previousPageName: VRS.MobilePageName.AircraftList, previousPageLabelKey: 'PageListShort', titleLabelKey: 'TitleAircraftDetail', nextPageName: VRS.MobilePageName.Map, nextPageLabelKey: 'PageMapShort', headerMenu: pageSettings.settingsMenu, showFooterGap: true })); VRS.pageManager.addPage(new VRS.Page({ name: VRS.MobilePageName.AircraftDetail, element: pageSettings.aircraftDetailPagePanelJQ, visibleCallback: function(isVisible) { var aircraftDetailPlugin = VRS.jQueryUIHelper.getAircraftDetailPlugin(pageSettings.aircraftDetailJQ); aircraftDetailPlugin.suspend(!isVisible); } })); } if(pageSettings.aircraftListJQ) { pageSettings.aircraftListPagePanelJQ = $('<div/>') .appendTo($('body')) .vrsPagePanel(VRS.jQueryUIHelper.getPagePanelOptions({ element: pageSettings.aircraftListJQ, previousPageName: VRS.MobilePageName.Map, previousPageLabelKey: 'PageMapShort', titleLabelKey: 'TitleAircraftList', nextPageName: VRS.MobilePageName.AircraftDetail, nextPageLabelKey: 'AircraftDetailShort', headerMenu: pageSettings.settingsMenu })); VRS.pageManager.addPage(new VRS.Page({ name: VRS.MobilePageName.AircraftList, element: pageSettings.aircraftListPagePanelJQ, visibleCallback: function(isVisible) { var aircraftListPlugin = VRS.jQueryUIHelper.getAircraftListPlugin(pageSettings.aircraftListJQ); aircraftListPlugin.suspend(!isVisible); } })); } if(this._Settings.showOptionsInPage) { var optionsContainer = $('<div/>'); var pausedStateWhenMadeVisible = false; pageSettings.optionsPagePanelJQ = $('<div/>') .appendTo('body') .vrsPagePanel(VRS.jQueryUIHelper.getPagePanelOptions({ element: optionsContainer, previousPageName: VRS.MobilePageName.Map, previousPageLabelKey: 'PageMapShort', titleLabelKey: 'Options', nextPageName: VRS.MobilePageName.AircraftList, nextPageLabelKey: 'PageListShort' })); VRS.pageManager.addPage(new VRS.Page({ name: VRS.MobilePageName.Options, element: pageSettings.optionsPagePanelJQ, visibleCallback: (isVisible) => { if(!isVisible) { var plugin = VRS.jQueryUIHelper.getOptionFormPlugin(optionsContainer); if(plugin) { plugin.destroy(); } if(pageSettings.aircraftListFetcher) { pageSettings.aircraftListFetcher.setPaused(pausedStateWhenMadeVisible); } } else { if(pageSettings.aircraftListFetcher) { pausedStateWhenMadeVisible = pageSettings.aircraftListFetcher.getPaused(); if(!pausedStateWhenMadeVisible) { pageSettings.aircraftListFetcher.setPaused(true); } } this.buildOptionPanelPages(pageSettings); optionsContainer.vrsOptionForm(VRS.jQueryUIHelper.getOptionFormOptions({ pages: pageSettings.pages, showInAccordion: true })); } } })); } this.raisePageManagerInitialised(pageSettings); } } }
the_stack
import { ClientSecretCredential } from '@azure/identity'; import { CryptographyClient, KeyWrapAlgorithm, KeyClient, KeyVaultKey } from '@azure/keyvault-keys'; import { createHash } from 'crypto'; import { parse } from 'url'; interface ParsedKeyPath { vaultUrl: string; name: string; version?: string | undefined; } export class ColumnEncryptionAzureKeyVaultProvider { public readonly name: string; private url: undefined | string; private readonly rsaEncryptionAlgorithmWithOAEPForAKV: string; private readonly firstVersion: Buffer; private credentials: ClientSecretCredential; private readonly azureKeyVaultDomainName: string; private keyClient: undefined | KeyClient; constructor(clientId: string, clientKey: string, tenantId: string) { this.name = 'AZURE_KEY_VAULT'; this.azureKeyVaultDomainName = 'vault.azure.net'; this.rsaEncryptionAlgorithmWithOAEPForAKV = 'RSA-OAEP'; this.firstVersion = Buffer.from([0x01]); this.credentials = new ClientSecretCredential(tenantId, clientId, clientKey); } async decryptColumnEncryptionKey(masterKeyPath: string, encryptionAlgorithm: string, encryptedColumnEncryptionKey: Buffer): Promise<Buffer> { if (!encryptedColumnEncryptionKey) { throw new Error('Internal error. Encrypted column encryption key cannot be null.'); } if (encryptedColumnEncryptionKey.length === 0) { throw new Error('Internal error. Empty encrypted column encryption key specified.'); } encryptionAlgorithm = this.validateEncryptionAlgorithm(encryptionAlgorithm); const masterKey = await this.getMasterKey(masterKeyPath); const keySizeInBytes = this.getAKVKeySize(masterKey); const cryptoClient = this.createCryptoClient(masterKey); if (encryptedColumnEncryptionKey[0] !== this.firstVersion[0]) { throw new Error(`Specified encrypted column encryption key contains an invalid encryption algorithm version ${Buffer.from([encryptedColumnEncryptionKey[0]]).toString('hex')}. Expected version is ${Buffer.from([this.firstVersion[0]]).toString('hex')}.`); } let currentIndex = this.firstVersion.length; const keyPathLength: number = encryptedColumnEncryptionKey.readInt16LE(currentIndex); currentIndex += 2; const cipherTextLength: number = encryptedColumnEncryptionKey.readInt16LE(currentIndex); currentIndex += 2; currentIndex += keyPathLength; if (cipherTextLength !== keySizeInBytes) { throw new Error(`The specified encrypted column encryption key's ciphertext length: ${cipherTextLength} does not match the ciphertext length: ${keySizeInBytes} when using column master key (Azure Key Vault key) in ${masterKeyPath}. The encrypted column encryption key may be corrupt, or the specified Azure Key Vault key path may be incorrect.`); } const signatureLength: number = encryptedColumnEncryptionKey.length - currentIndex - cipherTextLength; if (signatureLength !== keySizeInBytes) { throw new Error(`The specified encrypted column encryption key's signature length: ${signatureLength} does not match the signature length: ${keySizeInBytes} when using column master key (Azure Key Vault key) in ${masterKeyPath}. The encrypted column encryption key may be corrupt, or the specified Azure Key Vault key path may be incorrect.`); } const cipherText = Buffer.alloc(cipherTextLength); encryptedColumnEncryptionKey.copy(cipherText, 0, currentIndex, currentIndex + cipherTextLength); currentIndex += cipherTextLength; const signature = Buffer.alloc(signatureLength); encryptedColumnEncryptionKey.copy(signature, 0, currentIndex, currentIndex + signatureLength); const hash = Buffer.alloc(encryptedColumnEncryptionKey.length - signature.length); encryptedColumnEncryptionKey.copy(hash, 0, 0, encryptedColumnEncryptionKey.length - signature.length); const messageDigest = createHash('sha256'); messageDigest.update(hash); const dataToVerify: Buffer = messageDigest.digest(); if (!dataToVerify) { throw new Error('Hash should not be null while decrypting encrypted column encryption key.'); } const verifyKey = await cryptoClient.verify('RS256', dataToVerify, signature); if (!verifyKey.result) { throw new Error(`The specified encrypted column encryption key signature does not match the signature computed with the column master key (Asymmetric key in Azure Key Vault) in ${masterKeyPath}. The encrypted column encryption key may be corrupt, or the specified path may be incorrect.`); } const decryptedCEK: Buffer = await this.azureKeyVaultUnWrap(cryptoClient, encryptionAlgorithm, cipherText); return decryptedCEK; } async encryptColumnEncryptionKey(masterKeyPath: string, encryptionAlgorithm: string, columnEncryptionKey: Buffer): Promise<Buffer> { if (!columnEncryptionKey) { throw new Error('Column encryption key cannot be null.'); } if (columnEncryptionKey.length === 0) { throw new Error('Empty column encryption key specified.'); } encryptionAlgorithm = this.validateEncryptionAlgorithm(encryptionAlgorithm); const masterKey = await this.getMasterKey(masterKeyPath); const keySizeInBytes = this.getAKVKeySize(masterKey); const cryptoClient = this.createCryptoClient(masterKey); const version = Buffer.from([this.firstVersion[0]]); const masterKeyPathBytes: Buffer = Buffer.from(masterKeyPath.toLowerCase(), 'utf8'); const keyPathLength: Buffer = Buffer.alloc(2); keyPathLength[0] = masterKeyPathBytes.length & 0xff; keyPathLength[1] = masterKeyPathBytes.length >> 8 & 0xff; const cipherText: Buffer = await this.azureKeyVaultWrap(cryptoClient, encryptionAlgorithm, columnEncryptionKey); const cipherTextLength: Buffer = Buffer.alloc(2); cipherTextLength[0] = cipherText.length & 0xff; cipherTextLength[1] = cipherText.length >> 8 & 0xff; if (cipherText.length !== keySizeInBytes) { throw new Error('CipherText length does not match the RSA key size.'); } const dataToHash: Buffer = Buffer.alloc(version.length + keyPathLength.length + cipherTextLength.length + masterKeyPathBytes.length + cipherText.length); let destinationPosition: number = version.length; version.copy(dataToHash, 0, 0, version.length); keyPathLength.copy(dataToHash, destinationPosition, 0, keyPathLength.length); destinationPosition += keyPathLength.length; cipherTextLength.copy(dataToHash, destinationPosition, 0, cipherTextLength.length); destinationPosition += cipherTextLength.length; masterKeyPathBytes.copy(dataToHash, destinationPosition, 0, masterKeyPathBytes.length); destinationPosition += masterKeyPathBytes.length; cipherText.copy(dataToHash, destinationPosition, 0, cipherText.length); const messageDigest = createHash('sha256'); messageDigest.update(dataToHash); const dataToSign: Buffer = messageDigest.digest(); const signedHash: Buffer = await this.azureKeyVaultSignedHashedData(cryptoClient, dataToSign); if (signedHash.length !== keySizeInBytes) { throw new Error('Signed hash length does not match the RSA key size.'); } const verifyKey = await cryptoClient.verify('RS256', dataToSign, signedHash); if (!verifyKey.result) { throw new Error('Invalid signature of the encrypted column encryption key computed.'); } const encryptedColumnEncryptionKeyLength: number = version.length + cipherTextLength.length + keyPathLength.length + cipherText.length + masterKeyPathBytes.length + signedHash.length; const encryptedColumnEncryptionKey: Buffer = Buffer.alloc(encryptedColumnEncryptionKeyLength); let currentIndex = 0; version.copy(encryptedColumnEncryptionKey, currentIndex, 0, version.length); currentIndex += version.length; keyPathLength.copy(encryptedColumnEncryptionKey, currentIndex, 0, keyPathLength.length); currentIndex += keyPathLength.length; cipherTextLength.copy(encryptedColumnEncryptionKey, currentIndex, 0, cipherTextLength.length); currentIndex += cipherTextLength.length; masterKeyPathBytes.copy(encryptedColumnEncryptionKey, currentIndex, 0, masterKeyPathBytes.length); currentIndex += masterKeyPathBytes.length; cipherText.copy(encryptedColumnEncryptionKey, currentIndex, 0, cipherText.length); currentIndex += cipherText.length; signedHash.copy(encryptedColumnEncryptionKey, currentIndex, 0, signedHash.length); return encryptedColumnEncryptionKey; } private async getMasterKey(masterKeyPath: string): Promise<KeyVaultKey> { if (!masterKeyPath) { throw new Error('Master key path cannot be null or undefined'); } const keyParts = this.parsePath(masterKeyPath); this.createKeyClient(keyParts.vaultUrl); return (this.keyClient as KeyClient).getKey(keyParts.name, keyParts.version ? { version: keyParts.version } : {}); } private createKeyClient(keyVaultUrl: string): void { if (!keyVaultUrl) { throw new Error('Cannot create key client with null or undefined keyVaultUrl'); } if (!this.keyClient) { this.url = keyVaultUrl; this.keyClient = new KeyClient(keyVaultUrl, this.credentials); } } private createCryptoClient(masterKey: KeyVaultKey): CryptographyClient { if (!masterKey) { throw new Error('Cannot create CryptographyClient with null or undefined masterKey'); } return new CryptographyClient(masterKey, this.credentials); } private parsePath(masterKeyPath: string): ParsedKeyPath { if (!masterKeyPath || masterKeyPath.trim() === '') { throw new Error('Azure Key Vault key path cannot be null.'); } let baseUri; try { baseUri = parse(masterKeyPath, true, true); } catch { throw new Error(`Invalid keys identifier: ${masterKeyPath}. Not a valid URI`); } if (!baseUri.hostname || !baseUri.hostname.toLowerCase().endsWith(this.azureKeyVaultDomainName)) { throw new Error(`Invalid Azure Key Vault key path specified: ${masterKeyPath}.`); } // Path is of the form '/collection/name[/version]' const segments = (baseUri.pathname || '').split('/'); if (segments.length !== 3 && segments.length !== 4) { throw new Error( `Invalid keys identifier: ${masterKeyPath}. Bad number of segments: ${segments.length}` ); } if ('keys' !== segments[1]) { throw new Error( `Invalid keys identifier: ${masterKeyPath}. segment [1] should be "keys", found "${segments[1]}"` ); } const vaultUrl = `${baseUri.protocol}//${baseUri.host}`; const name = segments[2]; const version = segments.length === 4 ? segments[3] : undefined; return { vaultUrl, name, version }; } private async azureKeyVaultSignedHashedData(cryptoClient: CryptographyClient, dataToSign: Buffer): Promise<Buffer> { if (!cryptoClient) { throw new Error('Azure KVS Crypto Client is not defined.'); } const signedData = await cryptoClient.sign('RS256', dataToSign); return Buffer.from(signedData.result); } private async azureKeyVaultWrap(cryptoClient: CryptographyClient, encryptionAlgorithm: string, columnEncryptionKey: Buffer): Promise<Buffer> { if (!cryptoClient) { throw new Error('Azure KVS Crypto Client is not defined.'); } if (!columnEncryptionKey) { throw new Error('Column encryption key cannot be null.'); } const wrappedKey = await cryptoClient.wrapKey(encryptionAlgorithm as KeyWrapAlgorithm, columnEncryptionKey); return Buffer.from(wrappedKey.result); } private async azureKeyVaultUnWrap(cryptoClient: CryptographyClient, encryptionAlgorithm: string, encryptedColumnEncryptionKey: Buffer): Promise<Buffer> { if (!cryptoClient) { throw new Error('Azure KVS Crypto Client is not defined.'); } if (!encryptionAlgorithm) { throw new Error('Encryption Algorithm cannot be null or undefined'); } if (!encryptedColumnEncryptionKey) { throw new Error('Encrypted column encryption key cannot be null.'); } if (encryptedColumnEncryptionKey.length === 0) { throw new Error('Encrypted Column Encryption Key length should not be zero.'); } const unwrappedKey = await cryptoClient.unwrapKey(encryptionAlgorithm as KeyWrapAlgorithm, encryptedColumnEncryptionKey); return Buffer.from(unwrappedKey.result); } private getAKVKeySize(retrievedKey: KeyVaultKey): number { if (!retrievedKey) { throw new Error('Retrieved key cannot be null or undefined'); } const key = retrievedKey.key; if (!key) { throw new Error(`Key does not exist ${retrievedKey.name}`); } const kty: string | undefined = key && key.kty && key.kty.toString().toUpperCase(); if (!kty || 'RSA'.localeCompare(kty, 'en') !== 0) { throw new Error(`Cannot use a non-RSA key: ${kty}.`); } const keyLength = key && key.n && key.n.length; return keyLength || 0; } private validateEncryptionAlgorithm(encryptionAlgorithm: string): string { if (!encryptionAlgorithm) { throw new Error('Key encryption algorithm cannot be null.'); } if ('RSA_OAEP'.localeCompare(encryptionAlgorithm.toUpperCase(), 'en') === 0) { encryptionAlgorithm = 'RSA-OAEP'; } if (this.rsaEncryptionAlgorithmWithOAEPForAKV.localeCompare(encryptionAlgorithm.trim().toUpperCase(), 'en') !== 0) { throw new Error(`Invalid key encryption algorithm specified: ${encryptionAlgorithm}. Expected value: ${this.rsaEncryptionAlgorithmWithOAEPForAKV}.`); } return encryptionAlgorithm; } }
the_stack
import { Component, Input, ViewChild, ElementRef } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/merge'; import 'rxjs/add/operator/retry'; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/combineLatest'; import 'rxjs/add/observable/of'; import { TranslateService } from '@ngx-translate/core'; import { FunctionInfo } from '../shared/models/function-info'; import { FunctionKey, FunctionKeys, HostKeys } from '../shared/models/function-key'; import { BusyStateComponent } from '../busy-state/busy-state.component'; import { BroadcastService } from '../shared/services/broadcast.service'; import { BroadcastEvent } from '../shared/models/broadcast-event'; import { PortalResources } from '../shared/models/portal-resources'; import { UtilitiesService } from '../shared/services/utilities.service'; import { AccessibilityHelper } from './../shared/Utilities/accessibility-helper'; import { FunctionAppService } from 'app/shared/services/function-app.service'; import { FunctionAppContextComponent } from 'app/shared/components/function-app-context-component'; import { Subscription } from 'rxjs/Subscription'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { FunctionService } from 'app/shared/services/function.service'; import { HostKeyTypes } from 'app/shared/models/constants'; @Component({ selector: 'function-keys', templateUrl: './function-keys.component.html', styleUrls: ['./function-keys.component.scss', '../table-function-monitor/table-function-monitor.component.scss'], }) export class FunctionKeysComponent extends FunctionAppContextComponent { @Input() autoSelect: boolean; @Input() adminKeys: boolean; @ViewChild(BusyStateComponent) busyState: BusyStateComponent; @ViewChild('newKeyInput') newKeyInput: ElementRef; public newKeyName: string; public newKeyValue: string; public validKey: boolean; public keys: Array<FunctionKey>; public addingNew: boolean; public disabled = false; private refreshSubject: ReplaySubject<void>; private functionInfo: FunctionInfo; public tableId: string; public keyNameIdPrefix: string; public keyActionLabelledByPrefix: string; constructor( broadcastService: BroadcastService, private _translateService: TranslateService, private _utilities: UtilitiesService, private _functionAppService: FunctionAppService, private _functionService: FunctionService ) { super('function-keys', _functionAppService, broadcastService, _functionService); this.validKey = false; this.keys = []; this._broadcastService.subscribe<FunctionInfo>(BroadcastEvent.ResetKeySelection, fi => { if ((fi && fi === this.functionInfo) || (!fi && !this.functionInfo)) { return; } this.keys.forEach(k => (k.selected = false)); }); this.refreshSubject = new ReplaySubject(1); this.refreshSubject.next(null); } setup(): Subscription { return this.viewInfoEvents .combineLatest(this.refreshSubject, (a, b) => a) .switchMap(viewInfo => { if (this.adminKeys) { return this._functionService.getHostKeys(viewInfo.context.site.id, true).map(r => { return { isSuccessful: r.isSuccessful, result: r.isSuccessful ? this._formatHostKeys(r.result) : { keys: [] }, error: r.error, }; }); } else if (viewInfo.functionInfo.isSuccessful) { this.functionInfo = viewInfo.functionInfo.result.properties; return this._functionService.getFunctionKeys(viewInfo.context.site.id, viewInfo.functionInfo.result.properties.name, true); } else { this.functionInfo = null; return Observable.of({ isSuccessful: true, result: { keys: [] }, error: null, }); } }) .subscribe(keysResult => { this.tableId = this.functionInfo ? 'functionKeys' : 'hostKeys'; this.keyNameIdPrefix = `keyNameLabel-${this.tableId}-`; this.keyActionLabelledByPrefix = `${this.tableId} ${this.keyNameIdPrefix}`; this.resetState(); if (keysResult.isSuccessful) { const keys = keysResult.result; keys.keys.forEach(k => (k.show = false)); for (let i = 0; i < this.keys.length; i++) { const newKey = keys.keys.find(k => k.name.toLocaleLowerCase() === this.keys[i].name.toLocaleLowerCase()); if (newKey) { newKey.selected = this.keys[i].selected; } } this.keys = keys.keys; } else { this.showComponentError({ errorId: keysResult.error.errorId, message: keysResult.error.message, resourceId: this.context.site.id, }); } this.clearBusyState(); }); } showOrHideNewKeyUi() { if (this.addingNew) { this.resetState(); } else { this.resetState(); this.addingNew = true; } } checkValidName(event: KeyboardEvent) { setTimeout(() => { if (this.newKeyName && !this.keys.find(k => k.name.toLocaleLowerCase() === this.newKeyName.toLocaleLowerCase())) { this.validKey = true; } else { this.validKey = false; } if (this.validKey && event.keyCode === 13) { this.saveNewKey(); } }, 5); } saveNewKey() { if (this.validKey) { this.setBusyState(); if (!!this.newKeyValue) { if (this.tableId === 'functionKeys') { this._functionService .createFunctionKey(this.context.site.id, this.functionInfo.name, this.newKeyName, this.newKeyValue) .subscribe(newKeyResult => { if (newKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: newKeyResult.error.errorId, message: newKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } else { this._functionService .createHostKey(this.context.site.id, this.newKeyName, this.newKeyValue, HostKeyTypes.functionKeys) .subscribe(newKeyResult => { if (newKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: newKeyResult.error.errorId, message: newKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } } else { // note (allisonm): current the new API doesn't support auto-generating a key value // if no value is provided we must use the old generation method via function runtime // this will be remedied with ANT84 APIs this._functionAppService .createKeyDeprecated(this.context, this.newKeyName, this.newKeyValue, this.functionInfo) .subscribe(newKeyResult => { if (newKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: newKeyResult.error.errorId, message: newKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } } } revokeKey(key: FunctionKey) { if (confirm(this._translateService.instant(PortalResources.functionKeys_revokeConfirmation, { name: key.name }))) { this.setBusyState(); if (this.tableId === 'functionKeys') { this._functionService.deleteFunctionKey(this.context.site.id, this.functionInfo.name, key.name).subscribe(deleteKeyResult => { if (deleteKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: deleteKeyResult.error.errorId, message: deleteKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } else { this._functionService.deleteHostKey(this.context.site.id, key.name, key.hostKeyType).subscribe(deleteKeyResult => { if (deleteKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: deleteKeyResult.error.errorId, message: deleteKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } } } renewKey(key: FunctionKey) { if (confirm(this._translateService.instant(PortalResources.functionKeys_renewConfirmation, { name: key.name }))) { this.setBusyState(); this._functionAppService.renewKey(this.context, key, this.functionInfo).subscribe(renewKeyResult => { if (renewKeyResult.isSuccessful) { this.refreshSubject.next(null); } else { this.showComponentError({ errorId: renewKeyResult.error.errorId, message: renewKeyResult.error.message, resourceId: this.context.site.id, }); this.clearBusyState(); } }); } } private _formatHostKeys(hostKeys: HostKeys): FunctionKeys { const masterKey: FunctionKey = { name: '_master', value: hostKeys.masterKey, hostKeyType: HostKeyTypes.masterKey }; hostKeys.functionKeys.keys.forEach((key, i) => { hostKeys.functionKeys.keys[i].hostKeyType = HostKeyTypes.functionKeys; }); hostKeys.systemKeys.keys.forEach((key, i) => { hostKeys.systemKeys.keys[i].hostKeyType = HostKeyTypes.systemKeys; }); return { keys: [masterKey].concat(hostKeys.functionKeys.keys).concat(hostKeys.systemKeys.keys) }; } copyKey(key: FunctionKey) { this._utilities.copyContentToClipboard(key.value); } resetState() { delete this.validKey; delete this.addingNew; delete this.newKeyName; delete this.newKeyValue; } setBusyState() { if (this.busyState) { this.busyState.setBusyState(); } } clearBusyState() { if (this.busyState) { this.busyState.clearBusyState(); } } keyDown(event: any, command: string, key: FunctionKey) { if (AccessibilityHelper.isEnterOrSpace(event)) { switch (command) { case 'showKey': { key.show = true; break; } case 'renewKey': { this.renewKey(key); break; } case 'revokeKey': { this.revokeKey(key); break; } case 'copyKey': { this.copyKey(key); break; } } } } }
the_stack
import { createDomain, createEvent, forward, is } from 'effector' import { createReEffectFactory } from './createReEffect' import { CancelledError, LimitExceededError, TimeoutError } from './error' import { QUEUE, RACE, TAKE_EVERY, TAKE_FIRST, TAKE_LAST } from './strategy' console.error = jest.fn() test('createReEffectFactory should be factory', () => { expect(typeof createReEffectFactory()).toBe('function') const createEffect = createDomain().createEffect expect(typeof createReEffectFactory(createEffect)).toBe('function') }) test('createReEffect should create Effect-like object', () => { const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, void>('test') expect(is.effect(reeffect)).toBe(true) expect(reeffect.shortName).toBe('test') expect(typeof reeffect.use).toBe('function') expect(typeof reeffect.watch).toBe('function') expect(typeof reeffect.prepend).toBe('function') expect(is.event(reeffect.done)).toBe(true) expect(is.event(reeffect.fail)).toBe(true) expect(is.event(reeffect.finally)).toBe(true) expect(is.store(reeffect.pending)).toBe(true) // additional properties expect(is.event(reeffect.cancelled)).toBe(true) expect(is.event(reeffect.cancel)).toBe(true) // reeffect should return promise expect(reeffect() instanceof Promise).toBe(true) }) test('createReEffect single successful operation', async () => { expect.assertions(4) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, string>({ async handler() { return new Promise<string>(resolve => setTimeout(() => resolve('test'), 10) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) const result = await reeffect({ strategy: TAKE_EVERY }) expect(result).toBe('test') expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: undefined, result: 'test', status: 'done', }) // done event expect(fn.mock.calls[1][0]).toEqual({ params: undefined, result: 'test', }) }) test('createReEffect single sync successful operation', async () => { expect.assertions(4) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, string>({ handler() { return 'test' }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) const result = await reeffect({ strategy: TAKE_EVERY }) expect(result).toBe('test') expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: undefined, result: 'test', status: 'done', }) // done event expect(fn.mock.calls[1][0]).toEqual({ params: undefined, result: 'test', }) }) test('createReEffect single failed operation', async () => { expect.assertions(4) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ async handler() { return new Promise<string>((_, reject) => setImmediate(() => reject('error')) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) try { await reeffect(42) } catch (error) { expect(error).toBe('error') } expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: 42, error: 'error', status: 'fail', }) // fail event expect(fn.mock.calls[1][0]).toEqual({ params: 42, error: 'error', }) }) test('createReEffect single sync failed operation', async () => { expect.assertions(4) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ handler() { // tslint:disable-next-line no-string-throw throw 'error' }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) try { await reeffect(42) } catch (error) { expect(error).toBe('error') } expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: 42, error: 'error', status: 'fail', }) // fail event expect(fn.mock.calls[1][0]).toEqual({ params: 42, error: 'error', }) }) test('createReEffect with TAKE_EVERY strategy', async () => { expect.assertions(7) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ async handler(params) { return new Promise<string>(resolve => setTimeout(() => resolve(`test${params}`), params) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([reeffect(11), reeffect(22)]) expect(result).toEqual(['test11', 'test22']) expect(fn).toHaveBeenCalledTimes(5) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // finally event expect(fn.mock.calls[2][0]).toEqual({ params: 22, result: 'test22', status: 'done', }) // done event expect(fn.mock.calls[3][0]).toEqual({ params: 22, result: 'test22', }) // pending expect(fn.mock.calls[4][0]).toEqual(false) }) test('createReEffect with TAKE_EVERY strategy with first one failed', async () => { expect.assertions(7) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ async handler(params) { return new Promise<string>((resolve, reject) => setTimeout( () => params === 11 ? reject(`reject${params}`) : resolve(`resolve${params}`), params ) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([ reeffect(11).catch(error => error), reeffect(22), ]) expect(result).toEqual(['reject11', 'resolve22']) expect(fn).toHaveBeenCalledTimes(5) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // finally event expect(fn.mock.calls[2][0]).toEqual({ params: 22, result: 'resolve22', status: 'done', }) // done event expect(fn.mock.calls[3][0]).toEqual({ params: 22, result: 'resolve22', }) // pending expect(fn.mock.calls[4][0]).toEqual(false) }) test('createReEffect with TAKE_FIRST strategy', async () => { expect.assertions(8) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ strategy: TAKE_FIRST, async handler(params) { return new Promise<string>(resolve => setImmediate(() => resolve(`test${params}`)) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([ reeffect(11), reeffect(22).catch(error => error), ]) expect(result).toEqual(['test11', expect.any(CancelledError)]) expect(fn).toHaveBeenCalledTimes(6) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // cancelled event expect(fn.mock.calls[2][0]).toEqual({ params: 22, error: expect.any(CancelledError), }) // finally event expect(fn.mock.calls[3][0]).toEqual({ params: 11, result: 'test11', status: 'done', }) // done event expect(fn.mock.calls[4][0]).toEqual({ params: 11, result: 'test11', }) // pending expect(fn.mock.calls[5][0]).toEqual(false) }) test('createReEffect with TAKE_LAST strategy', async () => { expect.assertions(8) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>('name', { strategy: TAKE_LAST, async handler(params) { return new Promise<string>(resolve => setImmediate(() => resolve(`test${params}`)) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([ reeffect(11).catch(error => error), reeffect(22), ]) expect(result).toEqual([expect.any(CancelledError), 'test22']) expect(fn).toHaveBeenCalledTimes(6) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // cancelled event expect(fn.mock.calls[2][0]).toEqual({ params: 11, error: expect.any(CancelledError), }) // finally event expect(fn.mock.calls[3][0]).toEqual({ params: 22, result: 'test22', status: 'done', }) // done event expect(fn.mock.calls[4][0]).toEqual({ params: 22, result: 'test22', }) // pending expect(fn.mock.calls[5][0]).toEqual(false) }) test('createReEffect with QUEUE strategy', async () => { expect.assertions(7) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>('test_queue_strategy', { strategy: QUEUE, async handler(params) { return new Promise<string>(resolve => setTimeout(() => resolve(`test${params}`), 100) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([reeffect(11), reeffect(22)]) expect(result).toEqual(['test11', 'test22']) expect(fn).toHaveBeenCalledTimes(5) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // finally event expect(fn.mock.calls[2][0]).toEqual({ params: 22, result: 'test22', status: 'done', }) // done event expect(fn.mock.calls[3][0]).toEqual({ params: 22, result: 'test22', }) // pending expect(fn.mock.calls[4][0]).toEqual(false) }) test('createReEffect with QUEUE strategy and cancel', async () => { expect.assertions(7) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>('test_queue_strategy', { strategy: QUEUE, async handler(params) { return new Promise<string>(resolve => setTimeout(() => resolve(`test${params}`), 1000) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const running = Promise.all([ reeffect(11).catch(error => error), reeffect(22).catch(error => error), ]) reeffect.cancel() const result = await running expect(result).toEqual([ expect.any(CancelledError), expect.any(CancelledError), ]) expect(fn).toHaveBeenCalledTimes(5) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // cancelled event expect(fn.mock.calls[2][0]).toEqual({ params: 11, error: expect.any(CancelledError), }) // cancelled event expect(fn.mock.calls[3][0]).toEqual({ params: 22, error: expect.any(CancelledError), }) // pending expect(fn.mock.calls[4][0]).toEqual(false) }) test('createReEffect with QUEUE strategy and change handler', async () => { expect.assertions(10) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>('test_queue_strategy', { strategy: QUEUE, async handler(params) { return new Promise<string>(resolve => setTimeout(() => resolve(`first${params}`), 100) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) reeffect(1).catch(error => error) const fx = reeffect(2).catch(error => error) reeffect.use( params => new Promise<string>(resolve => setTimeout(() => resolve(`second${params}`), 100) ) ) await fx await reeffect(3).catch(error => error) expect(fn).toHaveBeenCalledTimes(9) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // finally event expect(fn.mock.calls[2][0]).toEqual({ params: 2, result: 'first2', status: 'done', }) // done event expect(fn.mock.calls[3][0]).toEqual({ params: 2, result: 'first2', }) // pending expect(fn.mock.calls[4][0]).toEqual(false) expect(fn.mock.calls[5][0]).toEqual(true) // finally event expect(fn.mock.calls[6][0]).toEqual({ params: 3, result: 'second3', status: 'done', }) // done event expect(fn.mock.calls[7][0]).toEqual({ params: 3, result: 'second3', }) // pending expect(fn.mock.calls[8][0]).toEqual(false) }) test('createReEffect with RACE strategy', async () => { expect.assertions(8) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ feedback: true, async handler(params) { return new Promise<string>(resolve => setTimeout(() => resolve(`resolve${params}`), params) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const result = await Promise.all([ reeffect(1000).catch(error => error), reeffect(100, { strategy: RACE }), ]) expect(result).toEqual([expect.any(CancelledError), 'resolve100']) expect(fn).toHaveBeenCalledTimes(6) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // finally event expect(fn.mock.calls[2][0]).toEqual({ params: 100, strategy: RACE, result: 'resolve100', status: 'done', }) // done event expect(fn.mock.calls[3][0]).toEqual({ params: 100, strategy: RACE, result: 'resolve100', }) // cancelled event expect(fn.mock.calls[4][0]).toEqual({ params: 1000, strategy: TAKE_EVERY, error: expect.any(CancelledError), }) // pending expect(fn.mock.calls[5][0]).toEqual(false) }) test('createReEffect with manual cancellation', async () => { expect.assertions(7) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ async handler(params) { return new Promise<string>(resolve => setImmediate(() => resolve(`test${params}`)) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) reeffect.pending.watch(fn) const running = Promise.all([ reeffect(11).catch(error => error), reeffect(22).catch(error => error), ]) reeffect.cancel() const result = await running expect(result).toEqual([ expect.any(CancelledError), expect.any(CancelledError), ]) expect(fn).toHaveBeenCalledTimes(5) // pending expect(fn.mock.calls[0][0]).toEqual(false) expect(fn.mock.calls[1][0]).toEqual(true) // cancelled event expect(fn.mock.calls[2][0]).toEqual({ params: 11, error: expect.any(CancelledError), }) // cancelled event expect(fn.mock.calls[3][0]).toEqual({ params: 22, error: expect.any(CancelledError), }) // pending expect(fn.mock.calls[4][0]).toEqual(false) }) test('createReEffect with logic cancel callback', async () => { expect.assertions(3) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ async handler(params, onCancel) { let timeout onCancel(() => clearTimeout(timeout)) return new Promise<string>(resolve => { timeout = setTimeout(() => { fn(`logic${params}`) resolve(`test${params}`) }, 1) }) }, }) const result = await Promise.all([ reeffect(11).catch(error => error), reeffect(22, { strategy: TAKE_LAST }), ]) expect(result).toEqual([expect.any(CancelledError), 'test22']) expect(fn).toHaveBeenCalledTimes(1) expect(fn.mock.calls[0][0]).toEqual('logic22') }) test('createReEffect with limit', async () => { expect.assertions(1) const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ limit: 1, handler: () => new Promise<string>(resolve => setImmediate(() => resolve('test'))), }) const result = await Promise.all([ reeffect(11), reeffect(22).catch(error => error), ]) expect(result).toEqual(['test', expect.any(LimitExceededError)]) }) test('createReEffect use should change handler', async () => { expect.assertions(4) const handler1 = () => new Promise<string>(resolve => setImmediate(() => resolve('handler1'))) const handler2 = () => new Promise<string>(resolve => setImmediate(() => resolve('handler2'))) const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ handler: handler1 }) expect(reeffect.use.getCurrent()).toBe(handler1) expect(reeffect.use(handler2)).toBe(reeffect) expect(reeffect.use.getCurrent()).toBe(handler2) const result = await Promise.all([ reeffect(11), reeffect(22, TAKE_FIRST).catch(error => error), ]) expect(result).toEqual(['handler2', expect.any(CancelledError)]) }) test('synchronious exception in handler should reject operation', () => { expect.assertions(1) const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, void>() reeffect.use(() => { throw 'error' // tslint:disable-line no-string-throw }) return reeffect().catch(error => expect(error).toBe('error')) }) test('createReEffect with Effector API, success', async () => { expect.assertions(3) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, string>({ async handler() { return new Promise<string>(resolve => setImmediate(() => resolve('test'))) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) const event = createEvent() forward({ from: event, to: reeffect, }) event() await new Promise(resolve => setTimeout(resolve, 10)) expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: undefined, result: 'test', status: 'done', }) // done event expect(fn.mock.calls[1][0]).toEqual({ params: undefined, result: 'test', }) }) test('createReEffect with Effector API, failure', async () => { expect.assertions(3) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, string>({ async handler() { return new Promise<string>((_, reject) => setImmediate(() => reject('test')) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) const event = createEvent() forward({ from: event, to: reeffect, }) event() await new Promise(resolve => setTimeout(resolve, 10)) expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: undefined, error: 'test', status: 'fail', }) // done event expect(fn.mock.calls[1][0]).toEqual({ params: undefined, error: 'test', }) }) test('createReEffect with feedback', async () => { expect.assertions(4) const fn = jest.fn() const createReEffect = createReEffectFactory() const reeffect = createReEffect<void, string>({ feedback: true, async handler() { return new Promise<string>(resolve => setTimeout(() => resolve('test'), 10) ) }, }) reeffect.done.watch(fn) reeffect.fail.watch(fn) reeffect.cancelled.watch(fn) reeffect.finally.watch(fn) const result = await reeffect({ strategy: TAKE_EVERY }) expect(result).toBe('test') expect(fn).toHaveBeenCalledTimes(2) // finally event expect(fn.mock.calls[0][0]).toEqual({ params: undefined, strategy: TAKE_EVERY, result: 'test', status: 'done', }) // done event expect(fn.mock.calls[1][0]).toEqual({ params: undefined, strategy: TAKE_EVERY, result: 'test', }) }) test('createReEffect with default timeout', async () => { expect.assertions(1) const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ timeout: 100, handler: () => new Promise<string>(resolve => setTimeout(() => resolve('test'), 1000)), }) const result = await reeffect(22).catch(error => error) expect(result).toEqual(expect.any(TimeoutError)) }) test('createReEffect with effect timeout', async () => { expect.assertions(1) const createReEffect = createReEffectFactory() const reeffect = createReEffect<number, string>({ handler: () => new Promise<string>(resolve => setTimeout(() => resolve('test'), 100)), }) const result = await Promise.all([ reeffect({ params: 11, timeout: 10 }).catch(error => error), reeffect(22), reeffect(33, { timeout: 50 }).catch(error => error), ]) expect(result).toEqual([ expect.any(TimeoutError), 'test', expect.any(TimeoutError), ]) })
the_stack
// Attribute and score types, and functions on attribute scores. // // TODO: it would be nice to use fancier type system features here for // better checks and less duplication. For example, not enumerating names of // attributes as arrays as well as in types, and ensuring that the various // mappings are exact (cover all attributes, and don't contain extra fields). // Attributes exposed to users in Tune settings. import * as tinygradient from 'tinygradient'; export type SettingAttributeName = 'identityAttack' | 'insult' | 'profanity' | 'threat' | 'sexuallyExplicit'; export const SETTING_ATTRIBUTE_NAMES: Array<SettingAttributeName> = ['identityAttack', 'insult', 'profanity', 'threat', 'sexuallyExplicit']; // All attributes. export type AttributeName = SettingAttributeName | 'toxicity' | 'severeToxicity' | 'likelyToReject'; export const ATTRIBUTE_NAMES: Array<AttributeName> = (SETTING_ATTRIBUTE_NAMES as Array<AttributeName>).concat(['toxicity', 'severeToxicity', 'likelyToReject']); // Perspective API Attribute names. export type ApiAttributeName = 'TOXICITY' | 'SEVERE_TOXICITY' | 'IDENTITY_ATTACK' | 'INSULT' | 'PROFANITY' | 'THREAT' | 'SEXUALLY_EXPLICIT' | 'LIKELY_TO_REJECT'; export const API_ATTRIBUTE_NAMES: Array<ApiAttributeName> = [ 'TOXICITY', 'SEVERE_TOXICITY', 'IDENTITY_ATTACK', 'INSULT', 'PROFANITY', 'THREAT', 'SEXUALLY_EXPLICIT', 'LIKELY_TO_REJECT' ]; // A single attribute score. export interface AttributeScore { attribute: AttributeName; score: number; } // Scores for all attributes for a comment. export type AttributeScores = { [key in AttributeName]: number; }; // User's settings of which attributes are enabled. export type EnabledAttributes = { [key in SettingAttributeName]: boolean; }; // Mapping used to convert API attribute names to Tune Attribute type. type ApiToAttributeName = { [key in ApiAttributeName]: AttributeName; }; type AttributeToApiName = { [key in AttributeName]: ApiAttributeName; }; // TODO: can we just have 1 copy? const API_TO_ATTRIBUTE_NAME_MAP: ApiToAttributeName = { 'IDENTITY_ATTACK': 'identityAttack', 'INSULT': 'insult', 'PROFANITY': 'profanity', 'THREAT': 'threat', 'SEXUALLY_EXPLICIT': 'sexuallyExplicit', 'TOXICITY': 'toxicity', 'SEVERE_TOXICITY': 'severeToxicity', 'LIKELY_TO_REJECT': 'likelyToReject', }; const ATTRIBUTE_TO_API_NAME_MAP: AttributeToApiName = { 'identityAttack': 'IDENTITY_ATTACK', 'insult': 'INSULT', 'profanity': 'PROFANITY', 'threat': 'THREAT', 'sexuallyExplicit': 'SEXUALLY_EXPLICIT', 'toxicity': 'TOXICITY', 'severeToxicity': 'SEVERE_TOXICITY', 'likelyToReject': 'LIKELY_TO_REJECT', }; // Converts API Attribute name to field name used in AttributeScores type. export function convertApiAttributeName(apiAttribute: ApiAttributeName): AttributeName { const fieldName = API_TO_ATTRIBUTE_NAME_MAP[apiAttribute]; if (fieldName === undefined) { throw new Error('Unknown API attribute name:' + apiAttribute); } return fieldName; } // Convert AttributeName to API attribute name. export function convertAttributeToApiName(attribute: AttributeName): ApiAttributeName { return ATTRIBUTE_TO_API_NAME_MAP[attribute]; } // Mapping from AttributeName to strings (e.g., for displaying to the user). type AttributeToString = { [key in AttributeName]: string; }; // Converts AttributeScoreType to human-friendly names for display. export const ATTRIBUTE_NAME_MAP: AttributeToString = { 'identityAttack': 'Attack on identity', 'insult': 'Insult', 'profanity': 'Profanity', 'threat': 'Threat', 'sexuallyExplicit': 'Sexually explicit', 'toxicity': 'Toxic', 'severeToxicity': 'Toxic', // NOTE: this shouldn't be displayed to users. 'likelyToReject': 'Low quality', }; // 0 to 0.15: quiet // 0.15 to 0.38: low // 0.38 to 0.62: mediun // 0.62 to 0.85: loud // 0.85 to 1.0: blaring export const LOW_THRESHOLD = 0.15; export const MEDIUM_THRESHOLD = 0.38; export const LOUD_THRESHOLD = 0.62; export const BLARING_THRESHOLD = 0.85; // TODO: Typings for tinygradient seem to be broken? // Fix and then remove any cast. const gradient = tinygradient([ {color: '#512DA8', pos: 0}, {color: '#6B2999', pos: LOW_THRESHOLD}, {color: '#86268A', pos: MEDIUM_THRESHOLD}, {color: '#AF2075', pos: LOUD_THRESHOLD}, {color: '#C31D6A', pos: BLARING_THRESHOLD}, {color: '#D81B60', pos: 1} ] as any); // Returns the color gradient value at the specified threshold. // Dark purple-ish to bright pink-ish. export function colorGradient(threshold: number): string { return gradient.rgbAt(threshold).toRgbString(); } // When we don't know the scores (typically due to unsupported language), we // hide the comments when the threshold is below this level. const HIDE_COMMENTS_IN_UNSUPPORTED_LANGUAGE_THRESHOLD = 0.3; function allAttributesEnabled(enabledAttributes: EnabledAttributes): boolean { for (const attr in enabledAttributes) { if (!enabledAttributes[attr]) { return false; } } return true; } function noAttributesEnabled(enabledAttributes: EnabledAttributes): boolean { for (const attr in enabledAttributes) { if (enabledAttributes[attr]) { return false; } } return true; } function shouldConsiderAttribute(attribute: AttributeName, enabledAttributes: EnabledAttributes) : boolean { // Attribute was explicitly enabled. if (enabledAttributes[attribute]) { return true; } // Consider severe toxicity unless all attributes are disabled. if (attribute === 'severeToxicity' && (!noAttributesEnabled(enabledAttributes))) { return true; } return false; } function maxEnabledAttributeScore( scores: AttributeScores, enabledAttributes: EnabledAttributes, subtypesEnabled: boolean) : AttributeScore|null { if (!subtypesEnabled) { return { attribute: 'toxicity', score: scores.toxicity }; } let currentMax: AttributeScore|null = null; for (const attributeKey of Object.keys(scores)) { const attribute = attributeKey as AttributeName; const attributeScore = scores[attribute]; if (shouldConsiderAttribute(attribute, enabledAttributes) && (currentMax === null || attributeScore > currentMax.score)) { currentMax = { attribute: attribute, score: attributeScore }; } } return currentMax; } // Note: This doesn't clip, so if x is outside the [fromA, fromB] range, the // output will be outside the [toA, toB] range. export function linscale( x: number, [fromA, fromB]: [number, number], [toA, toB]: [number, number]) : number { const fracAlongOrigScale = (x - fromA) / (fromB - fromA); const valueAlongNewScale = fracAlongOrigScale * (toB - toA) + toA; return valueAlongNewScale; } // The following shouldHideCommentDueTo* functions return HideCommentDueToScores // if the comment should be hidden or null if the comment shouldn't be hidden // due to the given criteria. function shouldHideCommentDueToSevereToxicity( severeToxicityScore: number, maxAttributeScore: AttributeScore|null, threshold: number) : HideCommentDueToScores|null { const boundedThreshold = Math.max(threshold, BLARING_THRESHOLD); if (severeToxicityScore < boundedThreshold) { return null; } const status: HideCommentDueToScores = { kind: 'hideCommentDueToScores', attribute: 'severeToxicity', scaledScore: severeToxicityScore, }; if (maxAttributeScore !== null && maxAttributeScore.score >= LOUD_THRESHOLD) { // If there's a high subtype attribute score, we use that as the attribute // for display purposes. status.attribute = maxAttributeScore.attribute; } return status; } // We map the ML probability score range (0.4, 1.0) to the Tune dial range // between low and blaring. The goal is to map the "useful signal" to the dial // setting. Once scores go below ~0.4, we no longer have any confidence that the // comment classifies as any of the enabled attributes. export function scaleEnabledAttributeScore(score: number) { return linscale(score, [0.4, 1.0] /* from */, [LOW_THRESHOLD, BLARING_THRESHOLD] /* to */); } function shouldHideCommentDueToAttributeScore( attributeScore: AttributeScore|null, threshold: number) : HideCommentDueToScores|null { if (attributeScore === null || threshold > BLARING_THRESHOLD) { return null; } const boundedThreshold = Math.max(threshold, LOW_THRESHOLD); const scaledScore = scaleEnabledAttributeScore(attributeScore.score); if (scaledScore < boundedThreshold) { return null; } return { kind: 'hideCommentDueToScores', attribute: attributeScore.attribute, scaledScore: scaledScore, }; } // Comments are hidden due to low quality when the threshold is quite low (only // in the "Quiet" range of the dial). We use a combination of both toxicity and // likelyToReject scores to try to filter low quality comments. function shouldHideCommentDueToLowQuality(scores: AttributeScores, threshold: number) : HideCommentDueToScores|null { if (threshold > LOW_THRESHOLD) { return null; } // Hack: Likely to reject is very sensitive, so we scale it down a bit. const scaledLikelyToReject = scores.likelyToReject * 0.6; // The goal is to show comments that have *either* low likelytoReject score // (i.e. similar to NYT-accepted comment), *or* low toxicity score (i.e. // positive friendly stuff). Hide comments when they fail both criteria. if (scores.toxicity < threshold || scaledLikelyToReject < threshold) { return null; } return { kind: 'hideCommentDueToScores', attribute: 'toxicity', scaledScore: scores.toxicity, }; } // Response type for whether a comment should be hidden. // CommentVisibilityDecision is a "discriminated union" type, following the // pattern described here: // https://www.typescriptlang.org/docs/handbook/advanced-types.html export type CommentVisibilityDecision = ShowComment | HideCommentDueToScores | HideCommentDueToUnsupportedLanguage; interface HideCommentDueToScores { kind: 'hideCommentDueToScores'; attribute: AttributeName; scaledScore: number; } interface ShowComment { kind: 'showComment'; } interface HideCommentDueToUnsupportedLanguage { kind: 'hideCommentDueToUnsupportedLanguage'; } // Determines whether a comment with the given `scores` should be hidden for the // given `threshold` and `enabledAttributes`. export function getCommentVisibility( scores: AttributeScores, threshold: number, enabledAttributes: EnabledAttributes, subtypesEnabled: boolean) : CommentVisibilityDecision { const show_comment: CommentVisibilityDecision = { kind: 'showComment' }; // TODO: enable strict null checking. should make this unnecessary. if (scores === null || scores === undefined) { console.error('Error: called with null/undefined scores:', scores); return show_comment; } // Missing scores is ~always due to unsupported language. const unsupportedLanguage = Object.keys(scores).length === 0; if (unsupportedLanguage) { if (threshold < HIDE_COMMENTS_IN_UNSUPPORTED_LANGUAGE_THRESHOLD) { return {kind: 'hideCommentDueToUnsupportedLanguage'}; } else { return show_comment; } } const maxAttributeScore = maxEnabledAttributeScore(scores, enabledAttributes, subtypesEnabled); const severeToxicityHideReason = shouldHideCommentDueToSevereToxicity( scores.severeToxicity, maxAttributeScore, threshold); if (severeToxicityHideReason !== null) { return severeToxicityHideReason; } const attributeScoreHideReason = shouldHideCommentDueToAttributeScore( maxAttributeScore, threshold); if (attributeScoreHideReason !== null) { return attributeScoreHideReason; } const lowQualityHideReason = shouldHideCommentDueToLowQuality(scores, threshold); if (lowQualityHideReason !== null) { return lowQualityHideReason; } return show_comment; } // Note: these include trailing spaces so we can concatenate directly with // attribute name. const ATTRIBUTE_PREFIX_MAP: AttributeToString = { 'identityAttack': 'an', 'insult': 'an', 'profanity': '', 'threat': 'a', 'sexuallyExplicit': '', 'toxicity': '', 'severeToxicity': '', 'likelyToReject': '', }; function attributeWithPrefix(attribute: string): string { const prefix = ATTRIBUTE_PREFIX_MAP[attribute]; const friendlyAttribute = ATTRIBUTE_NAME_MAP[attribute].toLowerCase(); if (prefix) { return prefix + ' ' + friendlyAttribute; } else { return friendlyAttribute; } } // Returns text description of the CommentVisibilityDescription to be displayed // to the user. export function getHideReasonDescription(commentVisibility: CommentVisibilityDecision): string { if (commentVisibility.kind === 'showComment') { return ''; } else if (commentVisibility.kind === 'hideCommentDueToUnsupportedLanguage') { return 'Tune doesn\'t currently support this language.'; } else if (commentVisibility.kind === 'hideCommentDueToScores') { if (commentVisibility.scaledScore >= BLARING_THRESHOLD) { return 'Blaring'; } else if (commentVisibility.scaledScore >= LOUD_THRESHOLD) { return 'Loud'; } else if (commentVisibility.scaledScore >= MEDIUM_THRESHOLD) { return 'Medium'; } else if (commentVisibility.scaledScore >= LOW_THRESHOLD) { return 'Low'; } else { return 'Quiet'; } } else { // Static check that we handled all possible cases. const _shouldntHappen: never = commentVisibility; return _shouldntHappen; } } export function getFeedbackQuestion(commentVisibility: CommentVisibilityDecision, subtypesEnabled: boolean) : string { if (commentVisibility.kind === 'showComment') { return ''; } if (subtypesEnabled && commentVisibility.kind === 'hideCommentDueToScores' && commentVisibility.scaledScore >= LOUD_THRESHOLD) { return 'Is this ' + attributeWithPrefix(commentVisibility.attribute) + '?'; } return 'Should this be hidden?'; }
the_stack
* [numberOfDataBlocks, dataCodewordsPerblock] */ export type GroupDataCodewordsConfig = [number, number] export interface ECCodewordsConfig { ecCodewordsPerBlock: number groups: GroupDataCodewordsConfig[] } export const ecCodewordsPerVersion: Record<string, ECCodewordsConfig> = { '1L': { ecCodewordsPerBlock: 7, groups: [[1, 19]], }, '1M': { ecCodewordsPerBlock: 10, groups: [[1, 16]], }, '1Q': { ecCodewordsPerBlock: 13, groups: [[1, 13]], }, '1H': { ecCodewordsPerBlock: 17, groups: [[1, 9]], }, '2L': { ecCodewordsPerBlock: 10, groups: [[1, 34]], }, '2M': { ecCodewordsPerBlock: 16, groups: [[1, 28]], }, '2Q': { ecCodewordsPerBlock: 22, groups: [[1, 22]], }, '2H': { ecCodewordsPerBlock: 28, groups: [[1, 16]], }, '3L': { ecCodewordsPerBlock: 15, groups: [[1, 55]], }, '3M': { ecCodewordsPerBlock: 26, groups: [[1, 44]], }, '3Q': { ecCodewordsPerBlock: 18, groups: [[2, 17]], }, '3H': { ecCodewordsPerBlock: 22, groups: [[2, 13]], }, '4L': { ecCodewordsPerBlock: 20, groups: [[1, 80]], }, '4M': { ecCodewordsPerBlock: 18, groups: [[2, 32]], }, '4Q': { ecCodewordsPerBlock: 26, groups: [[2, 24]], }, '4H': { ecCodewordsPerBlock: 16, groups: [[4, 9]], }, '5L': { ecCodewordsPerBlock: 26, groups: [[1, 108]], }, '5M': { ecCodewordsPerBlock: 24, groups: [[2, 43]], }, '5Q': { ecCodewordsPerBlock: 18, groups: [ [2, 15], [2, 16], ], }, '5H': { ecCodewordsPerBlock: 22, groups: [ [2, 11], [2, 12], ], }, '6L': { ecCodewordsPerBlock: 18, groups: [[2, 68]], }, '6M': { ecCodewordsPerBlock: 16, groups: [[4, 27]], }, '6Q': { ecCodewordsPerBlock: 24, groups: [[4, 19]], }, '6H': { ecCodewordsPerBlock: 28, groups: [[4, 15]], }, '7L': { ecCodewordsPerBlock: 20, groups: [[2, 78]], }, '7M': { ecCodewordsPerBlock: 18, groups: [[4, 31]], }, '7Q': { ecCodewordsPerBlock: 18, groups: [ [2, 14], [4, 15], ], }, '7H': { ecCodewordsPerBlock: 26, groups: [ [4, 13], [1, 14], ], }, '8L': { ecCodewordsPerBlock: 24, groups: [[2, 97]], }, '8M': { ecCodewordsPerBlock: 22, groups: [ [2, 38], [2, 39], ], }, '8Q': { ecCodewordsPerBlock: 22, groups: [ [4, 18], [2, 19], ], }, '8H': { ecCodewordsPerBlock: 26, groups: [ [4, 14], [2, 15], ], }, '9L': { ecCodewordsPerBlock: 30, groups: [[2, 116]], }, '9M': { ecCodewordsPerBlock: 22, groups: [ [3, 36], [2, 37], ], }, '9Q': { ecCodewordsPerBlock: 20, groups: [ [4, 16], [4, 17], ], }, '9H': { ecCodewordsPerBlock: 24, groups: [ [4, 12], [4, 13], ], }, '10L': { ecCodewordsPerBlock: 18, groups: [ [2, 68], [2, 69], ], }, '10M': { ecCodewordsPerBlock: 26, groups: [ [4, 43], [1, 44], ], }, '10Q': { ecCodewordsPerBlock: 24, groups: [ [6, 19], [2, 20], ], }, '10H': { ecCodewordsPerBlock: 28, groups: [ [6, 15], [2, 16], ], }, '11L': { ecCodewordsPerBlock: 20, groups: [[4, 81]], }, '11M': { ecCodewordsPerBlock: 30, groups: [ [1, 50], [4, 51], ], }, '11Q': { ecCodewordsPerBlock: 28, groups: [ [4, 22], [4, 23], ], }, '11H': { ecCodewordsPerBlock: 24, groups: [ [3, 12], [8, 13], ], }, '12L': { ecCodewordsPerBlock: 24, groups: [ [2, 92], [2, 93], ], }, '12M': { ecCodewordsPerBlock: 22, groups: [ [6, 36], [2, 37], ], }, '12Q': { ecCodewordsPerBlock: 26, groups: [ [4, 20], [6, 21], ], }, '12H': { ecCodewordsPerBlock: 28, groups: [ [7, 14], [4, 15], ], }, '13L': { ecCodewordsPerBlock: 26, groups: [[4, 107]], }, '13M': { ecCodewordsPerBlock: 22, groups: [ [8, 37], [1, 38], ], }, '13Q': { ecCodewordsPerBlock: 24, groups: [ [8, 20], [4, 21], ], }, '13H': { ecCodewordsPerBlock: 22, groups: [ [12, 11], [4, 12], ], }, '14L': { ecCodewordsPerBlock: 30, groups: [ [3, 115], [1, 116], ], }, '14M': { ecCodewordsPerBlock: 24, groups: [ [4, 40], [5, 41], ], }, '14Q': { ecCodewordsPerBlock: 20, groups: [ [11, 16], [5, 17], ], }, '14H': { ecCodewordsPerBlock: 24, groups: [ [11, 12], [5, 13], ], }, '15L': { ecCodewordsPerBlock: 22, groups: [ [5, 87], [1, 88], ], }, '15M': { ecCodewordsPerBlock: 24, groups: [ [5, 41], [5, 42], ], }, '15Q': { ecCodewordsPerBlock: 30, groups: [ [5, 24], [7, 25], ], }, '15H': { ecCodewordsPerBlock: 24, groups: [ [11, 12], [7, 13], ], }, '16L': { ecCodewordsPerBlock: 24, groups: [ [5, 98], [1, 99], ], }, '16M': { ecCodewordsPerBlock: 28, groups: [ [7, 45], [3, 46], ], }, '16Q': { ecCodewordsPerBlock: 24, groups: [ [15, 19], [2, 20], ], }, '16H': { ecCodewordsPerBlock: 30, groups: [ [3, 15], [13, 16], ], }, '17L': { ecCodewordsPerBlock: 28, groups: [ [1, 107], [5, 108], ], }, '17M': { ecCodewordsPerBlock: 28, groups: [ [10, 46], [1, 47], ], }, '17Q': { ecCodewordsPerBlock: 28, groups: [ [1, 22], [15, 23], ], }, '17H': { ecCodewordsPerBlock: 28, groups: [ [2, 14], [17, 15], ], }, '18L': { ecCodewordsPerBlock: 30, groups: [ [5, 120], [1, 121], ], }, '18M': { ecCodewordsPerBlock: 26, groups: [ [9, 43], [4, 44], ], }, '18Q': { ecCodewordsPerBlock: 28, groups: [ [17, 22], [1, 23], ], }, '18H': { ecCodewordsPerBlock: 28, groups: [ [2, 14], [19, 15], ], }, '19L': { ecCodewordsPerBlock: 28, groups: [ [3, 113], [4, 114], ], }, '19M': { ecCodewordsPerBlock: 26, groups: [ [3, 44], [11, 45], ], }, '19Q': { ecCodewordsPerBlock: 26, groups: [ [17, 21], [4, 22], ], }, '19H': { ecCodewordsPerBlock: 26, groups: [ [9, 13], [16, 14], ], }, '20L': { ecCodewordsPerBlock: 28, groups: [ [3, 107], [5, 108], ], }, '20M': { ecCodewordsPerBlock: 26, groups: [ [3, 41], [13, 42], ], }, '20Q': { ecCodewordsPerBlock: 30, groups: [ [15, 24], [5, 25], ], }, '20H': { ecCodewordsPerBlock: 28, groups: [ [15, 15], [10, 16], ], }, '21L': { ecCodewordsPerBlock: 28, groups: [ [4, 116], [4, 117], ], }, '21M': { ecCodewordsPerBlock: 26, groups: [[17, 42]], }, '21Q': { ecCodewordsPerBlock: 28, groups: [ [17, 22], [6, 23], ], }, '21H': { ecCodewordsPerBlock: 30, groups: [ [19, 16], [6, 17], ], }, '22L': { ecCodewordsPerBlock: 28, groups: [ [2, 111], [7, 112], ], }, '22M': { ecCodewordsPerBlock: 28, groups: [[17, 46]], }, '22Q': { ecCodewordsPerBlock: 30, groups: [ [7, 24], [16, 25], ], }, '22H': { ecCodewordsPerBlock: 24, groups: [[34, 13]], }, '23L': { ecCodewordsPerBlock: 30, groups: [ [4, 121], [5, 122], ], }, '23M': { ecCodewordsPerBlock: 28, groups: [ [4, 47], [14, 48], ], }, '23Q': { ecCodewordsPerBlock: 30, groups: [ [11, 24], [14, 25], ], }, '23H': { ecCodewordsPerBlock: 30, groups: [ [16, 15], [14, 16], ], }, '24L': { ecCodewordsPerBlock: 30, groups: [ [6, 117], [4, 118], ], }, '24M': { ecCodewordsPerBlock: 28, groups: [ [6, 45], [14, 46], ], }, '24Q': { ecCodewordsPerBlock: 30, groups: [ [11, 24], [16, 25], ], }, '24H': { ecCodewordsPerBlock: 30, groups: [ [30, 16], [2, 17], ], }, '25L': { ecCodewordsPerBlock: 26, groups: [ [8, 106], [4, 107], ], }, '25M': { ecCodewordsPerBlock: 28, groups: [ [8, 47], [13, 48], ], }, '25Q': { ecCodewordsPerBlock: 30, groups: [ [7, 24], [22, 25], ], }, '25H': { ecCodewordsPerBlock: 30, groups: [ [22, 15], [13, 16], ], }, '26L': { ecCodewordsPerBlock: 28, groups: [ [10, 114], [2, 115], ], }, '26M': { ecCodewordsPerBlock: 28, groups: [ [19, 46], [4, 47], ], }, '26Q': { ecCodewordsPerBlock: 28, groups: [ [28, 22], [6, 23], ], }, '26H': { ecCodewordsPerBlock: 30, groups: [ [33, 16], [4, 17], ], }, '27L': { ecCodewordsPerBlock: 30, groups: [ [8, 122], [4, 123], ], }, '27M': { ecCodewordsPerBlock: 28, groups: [ [22, 45], [3, 46], ], }, '27Q': { ecCodewordsPerBlock: 30, groups: [ [8, 23], [26, 24], ], }, '27H': { ecCodewordsPerBlock: 30, groups: [ [12, 15], [28, 16], ], }, '28L': { ecCodewordsPerBlock: 30, groups: [ [3, 117], [10, 118], ], }, '28M': { ecCodewordsPerBlock: 28, groups: [ [3, 45], [23, 46], ], }, '28Q': { ecCodewordsPerBlock: 30, groups: [ [4, 24], [31, 25], ], }, '28H': { ecCodewordsPerBlock: 30, groups: [ [11, 15], [31, 16], ], }, '29L': { ecCodewordsPerBlock: 30, groups: [ [7, 116], [7, 117], ], }, '29M': { ecCodewordsPerBlock: 28, groups: [ [21, 45], [7, 46], ], }, '29Q': { ecCodewordsPerBlock: 30, groups: [ [1, 23], [37, 24], ], }, '29H': { ecCodewordsPerBlock: 30, groups: [ [19, 15], [26, 16], ], }, '30L': { ecCodewordsPerBlock: 30, groups: [ [5, 115], [10, 116], ], }, '30M': { ecCodewordsPerBlock: 28, groups: [ [19, 47], [10, 48], ], }, '30Q': { ecCodewordsPerBlock: 30, groups: [ [15, 24], [25, 25], ], }, '30H': { ecCodewordsPerBlock: 30, groups: [ [23, 15], [25, 16], ], }, '31L': { ecCodewordsPerBlock: 30, groups: [ [13, 115], [3, 116], ], }, '31M': { ecCodewordsPerBlock: 28, groups: [ [2, 46], [29, 47], ], }, '31Q': { ecCodewordsPerBlock: 30, groups: [ [42, 24], [1, 25], ], }, '31H': { ecCodewordsPerBlock: 30, groups: [ [23, 15], [28, 16], ], }, '32L': { ecCodewordsPerBlock: 30, groups: [[17, 115]], }, '32M': { ecCodewordsPerBlock: 28, groups: [ [10, 46], [23, 47], ], }, '32Q': { ecCodewordsPerBlock: 30, groups: [ [10, 24], [35, 25], ], }, '32H': { ecCodewordsPerBlock: 30, groups: [ [19, 15], [35, 16], ], }, '33L': { ecCodewordsPerBlock: 30, groups: [ [17, 115], [1, 116], ], }, '33M': { ecCodewordsPerBlock: 28, groups: [ [14, 46], [21, 47], ], }, '33Q': { ecCodewordsPerBlock: 30, groups: [ [29, 24], [19, 25], ], }, '33H': { ecCodewordsPerBlock: 30, groups: [ [11, 15], [46, 16], ], }, '34L': { ecCodewordsPerBlock: 30, groups: [ [13, 115], [6, 116], ], }, '34M': { ecCodewordsPerBlock: 28, groups: [ [14, 46], [23, 47], ], }, '34Q': { ecCodewordsPerBlock: 30, groups: [ [44, 24], [7, 25], ], }, '34H': { ecCodewordsPerBlock: 30, groups: [ [59, 16], [1, 17], ], }, '35L': { ecCodewordsPerBlock: 30, groups: [ [12, 121], [7, 122], ], }, '35M': { ecCodewordsPerBlock: 28, groups: [ [12, 47], [26, 48], ], }, '35Q': { ecCodewordsPerBlock: 30, groups: [ [39, 24], [14, 25], ], }, '35H': { ecCodewordsPerBlock: 30, groups: [ [22, 15], [41, 16], ], }, '36L': { ecCodewordsPerBlock: 30, groups: [ [6, 121], [14, 122], ], }, '36M': { ecCodewordsPerBlock: 28, groups: [ [6, 47], [34, 48], ], }, '36Q': { ecCodewordsPerBlock: 30, groups: [ [46, 24], [10, 25], ], }, '36H': { ecCodewordsPerBlock: 30, groups: [ [2, 15], [64, 16], ], }, '37L': { ecCodewordsPerBlock: 30, groups: [ [17, 122], [4, 123], ], }, '37M': { ecCodewordsPerBlock: 28, groups: [ [29, 46], [14, 47], ], }, '37Q': { ecCodewordsPerBlock: 30, groups: [ [49, 24], [10, 25], ], }, '37H': { ecCodewordsPerBlock: 30, groups: [ [24, 15], [46, 16], ], }, '38L': { ecCodewordsPerBlock: 30, groups: [ [4, 122], [18, 123], ], }, '38M': { ecCodewordsPerBlock: 28, groups: [ [13, 46], [32, 47], ], }, '38Q': { ecCodewordsPerBlock: 30, groups: [ [48, 24], [14, 25], ], }, '38H': { ecCodewordsPerBlock: 30, groups: [ [42, 15], [32, 16], ], }, '39L': { ecCodewordsPerBlock: 30, groups: [ [20, 117], [4, 118], ], }, '39M': { ecCodewordsPerBlock: 28, groups: [ [40, 47], [7, 48], ], }, '39Q': { ecCodewordsPerBlock: 30, groups: [ [43, 24], [22, 25], ], }, '39H': { ecCodewordsPerBlock: 30, groups: [ [10, 15], [67, 16], ], }, '40L': { ecCodewordsPerBlock: 30, groups: [ [19, 118], [6, 119], ], }, '40M': { ecCodewordsPerBlock: 28, groups: [ [18, 47], [31, 48], ], }, '40Q': { ecCodewordsPerBlock: 30, groups: [ [34, 24], [34, 25], ], }, '40H': { ecCodewordsPerBlock: 30, groups: [ [20, 15], [61, 16], ], }, }
the_stack
'use strict'; module TDev { export class JsonExportCtx { constructor(public stackframe: IStackFrame, public fullcloudstate = false) { } private depth = 0; public push(node: RT.RTValue) { Util.assert(!node.jsonExportMark); node.jsonExportMark = true; this.depth++; } public pop(node: RT.RTValue) { Util.assert(node.jsonExportMark); node.jsonExportMark = false; this.depth--; } public encodeObjectNode(node: RT.RTValue, keys: string[], vals: any[]): any { Util.assert(keys.length == vals.length); var json = {}; var exportkey = node.jsonExportKey(this); if (exportkey) json["⌹id"] = exportkey; this.encodeValues(vals); for (var i = 0; i < vals.length; i++) { var val = vals[i]; if (val !== undefined) json[keys[i]] = val; } return json; } public encodeArrayNode(node: RT.RTValue, vals: any[]): any { Util.assert(!node.jsonExportKey(this)); this.encodeValues(vals); return vals; } private encodeValues(vals: any[]) { var recursed: RT.RTValue[]; // mark or prune recursive entries for (var i = 0; i < vals.length; i++) { var v = vals[i]; if (v && (v instanceof RT.RTValue)) { var k = v.jsonExportKey(this); if (k !== undefined) { // needs recursive encoding if (v.jsonExportMark || (this.fullcloudstate && this.depth > 0)) { vals[i] = k; } else { v.jsonExportMark = true; if (!recursed) recursed = new Array<RT.RTValue>(); recursed.push(v); } } } } // encode all entries for (var i = 0; i < vals.length; i++) { var val = vals[i]; if (val !== undefined && val !== null) { var t = typeof val; if (t == "function") vals[i] = undefined else if (t !== "boolean" && t !== "string" && t !== "number") vals[i] = val.exportJson(this); } } // unmark entries if (recursed) recursed.forEach((rv) => { Util.assert(rv.jsonExportMark); rv.jsonExportMark = false; }); } } export class JsonImportCtx { constructor(public s: IStackFrame) { } // mappings private mapping = {}; public map(table: string, id: string): string { return id ? (this.mapping[table+id] || id) : id; } public addmapping(table: string, from: string, to: string) { this.mapping[table + from] = to; } // basic value types public importString(source: any, key: any): string { var v = source ? source[key] : undefined; return (typeof v == "string") ? v : undefined; } public importNumber(source: any, key: any): number { var v = source ? source[key] : undefined; if (typeof v == "string") v = Number(v); return (typeof v == "number") ? v : undefined; } public importBoolean(source: any, key: any): boolean { var v = source ? source[key] : undefined; return (typeof v == "boolean") ? v : undefined; } // immutable RT types public importDateTime(source: any, key: any): RT.DateTime { var v = source ? source[key] : undefined; return RT.DateTime.mkFromJson(this, v); } public importColor(source: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; return RT.Color.mkFromJson(this, v); } public importJsonObject(source: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; return RT.JsonObject.mkFromJson(this, v); } public importLocation(source: any, key: any): RT.Location_ { var v = source ? source[key] : undefined; return RT.Location_.mkFromJson(this, v); } public importVector3(source: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; return RT.Vector3.mkFromJson(this, v); } public importUser(source: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; return RT.User.mkFromJson(this, v); } // collection types public importStringMap(source: any, target: any, key: any): RT.StringMap { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) target = new RT.StringMap(); return target.importJson(this, v); } public importNumberMap(source: any, target: any, key: any): RT.NumberMap { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) target = new RT.NumberMap(); return target.importJson(this, v); } public importCollection(source: any, target: any, key: any, typeInfo: any) { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) { target = RT.Collection.fromArray([], typeInfo) } return target.importJson(this, v); } // mutable RT types public importJsonBuilder(source: any, target: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) target = new (<any>RT.JsonBuilder)(); //TS9 return target.importJson(this, v); } public importLink(source: any, target: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) target = new RT.Link(); return target.importJson(this, v); } public importOAuthResponse(source: any, target: any, key: any): RT.RTValue { var v = source ? source[key] : undefined; if (!v) return undefined; if (!target) target = new RT.OAuthResponse(); return target.importJson(this, v); } // records public importRecord(source: any, target: any, key: any, singleton: RT.RecordSingleton): RT.RTValue { var v = source ? source[key] : undefined; if (!v) return undefined; return singleton.importJsonRecord(this, target, v, false); } /* public importValueField(obj: any, name: string, type: string) { } public importReferenceField(obj: any, name: string) { var val = obj[name]; val.importJson(this); } public importjson( getter: (sk: any, v: any) => any[], setter: (dk: any, v: any) => void, srckeys: any, json: any): void { var len = (typeof srckeys === 'number') ? srckeys : srckeys.length; var getkey = (typeof srckeys === 'number') ? (n: number) => n : (n: number) => srckeys[n]; for (var i = 0; i < len; i++) { var key = getkey(i); var val = json[key]; var importpair = getter(key, val); var destkey = importpair[0]; var importer = importpair[1]; switch (typeof (importer)) { case "function": val = importer(this, val); // general import function break; case "object": Util.assert(importer instanceof RT.RTValue); val = (<RT.RTValue>importer).importJson(this, val); break; case "number": if (typeof val !== "number") val = 0; break; case "boolean": if (typeof val !== "boolean") val = false; break; case "string": if (typeof val !== "string") val = ""; break; default: Util.oops("unhandled type: " + typeof(importer)); break; } setter(destkey, val); } } // import json array. Factory creates [key,val] or undefined if it should not be imported public importArray(obj: any, json: any[], key: (n: number) => any, factory: (n: number) => any[]): boolean { if (!Array.isArray(json)) return false; for (var i = 0; i < json.length; i++) { if (json[i] === null) continue; Util.assert(json[i] !== undefined); var k = key(i); var dest = obj[k]; if (dest === undefined || dest === null) { var keyvalpair = factory(i); if (!keyvalpair) continue; k = keyvalpair[0]; dest = keyvalpair[1]; } if (typeof (dest) != typeof (json[i])) continue; switch (typeof (dest)) { case "object": if (dest.importJson(this, json[i])) obj[k] = dest; break; case "number": case "boolean": case "string": obj[k] = json[i]; break; default: Util.oops("unhandled type"); break; } } return true; } */ // import json object. Factory creates val or undefined if it should not be imported //public importObject(obj: any, json: any, keys: any[], factory: (k: string) => any): boolean { // if (typeof (json) !== "object") // return false; // var keys = Object.keys(json); // return importArray(this, obj, keys.map((k) => json[k]), (n) => keys[n], (n) => { // var val = factory(keys[n]); // if (val !== undefined) // val = [keys[n], val]; // return val; // }); // } } }
the_stack
import * as assert from 'assert' import { Params, getAction, ActionType } from '../types' import { Handler, Processor, HandlerContext } from '../processor' import * as BUILT_IN_VALIDATORS from '../validators' import { AccessorInterface } from '../accessor' import { DefaultLogger, LoggerInterface } from '../logger' import { PermissionRule, PolicyInterface, ValidateError, ValidateResult } from './interface' /** * 访问规则结构: * DatabaseRule: * -> CollectionRule: * -> read: PermissionRule[] * -> add: PermissionRule[] * -> update: PermissionRule[] * -> remove: PermissionRule[] * -> count: PermissionRule[] * -> watch: PermissionRule[] */ export enum PermissionTypeV1 { READ = '.read', UPDATE = '.update', ADD = '.add', REMOVE = '.remove', COUNT = '.count' } export enum PermissionType { READ = 'read', UPDATE = 'update', ADD = 'add', REMOVE = 'remove', COUNT = 'count', WATCH = 'watch', AGGREGATE = 'aggregate' } // 数据库规则 export interface DatabaseRule { [collection: string]: CollectionRule } // 集合规则 export type CollectionRule = { // 集合数据的结构约束 $schema: PermissionRule[], read: PermissionRule[], add: PermissionRule[], update: PermissionRule[], remove: PermissionRule[], count: PermissionRule[], watch: PermissionRule[] } // 验证器容器 export interface ValidatorMap { [name: string]: Handler } export class Policy implements PolicyInterface { readonly version = 2 protected _accessor: AccessorInterface protected _logger: LoggerInterface /** * 验证器注册表 */ protected validators: ValidatorMap /** * 解析后的数据库规则树 */ protected rules: DatabaseRule private get logger() { if (!this._logger) { this._logger = new DefaultLogger(0) } return this._logger } public setLogger(logger: LoggerInterface) { this._logger = logger } get accessor(): AccessorInterface { return this._accessor } public setAccessor(accessor: AccessorInterface) { this._accessor = accessor } get collections() { if (!this.rules) return [] return Object.keys(this.rules) } constructor(accessor?: AccessorInterface) { this._accessor = accessor this.validators = {} this.rules = {} this.loadBuiltins() } /** * 加载 rules in json * @param rules any * @returns */ load(rules: any) { this.logger.debug(`load rules: `, JSON.stringify(rules)) assert.equal(typeof rules, 'object', "invalid 'rules'") // 处理每张数据库表的访问规则 for (let collection in rules) { this.add(collection, rules[collection]) } this.logger.info(`all rules loaded`) return true } /** * 添加一个集合的访问规则,同 {set()},但当集合已存在时,则添加失败 * @param collection 集合名称 * @param rules 集合的访问规则,是一个对象, like { "read": {...}, 'update': {...} } */ add(collection: string, rules: any) { if (this.collections.includes(collection)) { throw new Error(`add collection rules failed: ${collection} already exists`) } this.set(collection, rules) } /** * 设置一个集合的访问规则,若集合规则已存在,则替换其规则 * @param collection 集合名称 * @param rules 集合的访问规则,是一个对象, like { "read": {...}, 'update': {...} } */ set(collection: string, rules: any) { this.logger.info(`set collection rules: ${collection}...`) rules = this.convertPermissionConfig(rules) // 集合权限,是一个对象, like { "read": {...}, 'update': {...} } const collectionRule = {} as CollectionRule // 处理每种权限规则, like ['read', 'update' ...] const perm_types = Object.keys(rules) as PermissionType[] for (const ptype of perm_types) { // skip non-permisstion-type item, like '$schema' if (ptype as string === '$schema') { continue } // 权限对应的验证器配置, like { 'condition': true, 'data': {...} } const permissionConfig = rules[ptype] const permissionConfigArr = this.wrapRawPermissionRuleToArray(permissionConfig) // add schema config if ADD or UPDATE if ([PermissionType.ADD, PermissionType.UPDATE].includes(ptype)) { permissionConfigArr.forEach(pmc => { pmc['schema'] = rules['$schema'] }) } // instantiate validators collectionRule[ptype] = this.instantiateValidators(permissionConfigArr) } this.rules[collection] = collectionRule } /** * 转换 v1 版本的权限名到 v2 * example: * ".read" -> "read" * ".update" -> ".update" * ... * @param rules * @returns */ private convertPermissionConfig(rules: any): any { let newRules = {} for (const key in rules) { let type = key switch (key) { case PermissionTypeV1.READ: type = PermissionType.READ break case PermissionTypeV1.UPDATE: type = PermissionType.UPDATE break case PermissionTypeV1.ADD: type = PermissionType.ADD break case PermissionTypeV1.COUNT: type = PermissionType.COUNT break case PermissionTypeV1.REMOVE: type = PermissionType.REMOVE break } newRules[type] = rules[key] } return newRules } /** * normalize:将输入规则格式转为内部统一形式,即对象数组 * 1. boolean -> [{ condition: "bool string"}] * 2. string -> [{ condition: "expression string" }] * 3. object -> [ object ] * 4. array -> array * @param permissionRules * @returns */ private wrapRawPermissionRuleToArray(permissionRules: any): any[] { assert.notEqual(permissionRules, undefined, 'permissionRules is undefined') let rules = permissionRules // 权限规则为布尔时,默认使用 condition 验证器 if ([true, false].includes(rules)) { rules = [{ condition: `${rules}` }] } // 权限规则为字符串时,默认使用 condition 验证器 if (typeof rules === 'string') rules = [{ condition: rules }] // 权限规则不为数组时,转为数组 if (!(rules instanceof Array)) rules = [rules] return rules } /** * 实例化验证器 * @param permissionRules 权限规则 */ private instantiateValidators(rules: any[]): PermissionRule[] { const result: PermissionRule[] = rules.map(raw_rule => { const prule: PermissionRule = {} // 检查用户配置的验证器是否已注册 for (let vname in raw_rule) { const handler = this.validators[vname] if (!handler) { throw new Error(`unknown validator '${vname}' in your rules`) } } // 逐一实例化验证器 for (let vname in this.validators) { const handler = this.validators[vname] // 如果用户并未配置此验证器,则其配置缺省为 undefined,验证器实现时需处理缺省情况 const config = raw_rule[vname] prule[vname] = new Processor(vname, handler, config) } return prule }) return result } /** * 验证访问规则 * @param params * @param injections */ async validate(params: Params, injections: object): Promise<ValidateResult> { const { collection, action: actionType } = params this.logger.debug(`ruler validate with injections: `, injections) let errors: ValidateError[] = [] // 判断所访问的集合是否配置规则 if (!this.collections.includes(collection)) { this.logger.debug(`validate() ${collection} not in rules`) const err: ValidateError = { type: 0, error: `collection "${collection}" not found` } errors.push(err) return { errors } } // action 是否合法 const action = getAction(actionType) if (!action) { const err: ValidateError = { type: 0, error: `action "${actionType}" invalid` } errors.push(err) return { errors } } const permName = this.getPermissionName(action.type) const permRules: PermissionRule[] = this.rules[collection][permName] // if no permission rules if (!permRules) { const err: ValidateError = { type: 0, error: `${collection} ${actionType} don't has any rules` } errors.push(err) return { errors } } this.logger.trace(`${actionType} -> ${collection} permission rules: `, permRules) // loop for validating every permission rule let matched = null const context: HandlerContext = { ruler: this, params, injections } for (let validtrs of permRules) { let error: ValidateError = null // 执行一条规则的所有验证器 for (let vname in validtrs) { let result = await validtrs[vname].run(context) // 任一验证器执行不通过,则跳过本条规则 if (result) { error = { type: vname, error: result } break } } if (error) errors.push(error) // 本条规则验证通过 if (!error) { matched = validtrs break } } // return error if no permission rule matched if (!matched) { this.logger.debug(`validate rejected: ${actionType} -> ${collection} `) this.logger.trace(`validate errors: `, errors) return { errors } } this.logger.debug(`validate passed: ${actionType} -> ${collection} `) this.logger.trace(`matched: `, matched) return { matched } } /** * 注册验证器 * @param name * @param handler */ register(name: string, handler: Handler) { assert.ok(name, `register error: name must not be empty`) assert.ok(handler instanceof Function, `${name} register error: 'handler' must be a callable function`) const exists = Object.keys(this.validators).filter(vn => vn === name) assert.ok(!exists.length, `validator's name: '${name}' duplicated`) this.validators[name] = handler } /** * 加载内置验证器 */ private loadBuiltins() { for (let name in BUILT_IN_VALIDATORS) { const handler = BUILT_IN_VALIDATORS[name] as Handler this.register(name, handler) } } /** * 获取指定 ActionType 对应的权限名 * @param action ActionType * @returns */ private getPermissionName(action: ActionType): PermissionType { switch (action) { case ActionType.ADD: return PermissionType.ADD case ActionType.READ: return PermissionType.READ case ActionType.AGGREGATE: return PermissionType.AGGREGATE case ActionType.UPDATE: return PermissionType.UPDATE case ActionType.REMOVE: return PermissionType.REMOVE case ActionType.COUNT: return PermissionType.COUNT default: throw new Error('getPermissionName() unknown action') } } }
the_stack
declare var describe: any; import { test, testFolder } from './ExecutionHelper'; import { expect } from 'chai'; import { readBytes } from '../dist/utils/execution'; const getBytes = require('utf8-bytes'); describe('Execution tests', () => { describe('call indirect', () => { test( 'call indirect #1', ` fun a(): i32 = 10 fun b(): i32 = 20 fun caller(c: fun() -> i32): i32 = c() #[export] fun test(x: i32): void = { if (x == 1) { support::test::assert(caller(a) == 10, "Case a") } else { support::test::assert(caller(b) == 20, "Case b") } } `, async x => { x.exports.test(1); } ); }) describe('multiple impl', () => { test( 'two functions with different names', ` struct A() impl A { fun test1(): i32 = 1 } impl A { fun test2(): i32 = 2 } #[export] fun test(): void = { support::test::assert(A.test1() == 1, "test1") support::test::assert(A.test2() == 2, "test2") } `, async x => { x.exports.test(); } ); test( 'two functions with overloads in different impl', ` struct A() impl A { fun test(value: i32): i32 = value } impl A { fun test(value: boolean): i32 = -1 } #[export] fun test(): void = { support::test::assert(A.test(1) == 1, "test 1") support::test::assert(A.test(2) == 2, "test 2") support::test::assert(A.test(false) == -1, "test 3") } `, async x => { x.exports.test(); } ); test( 'implicit and explicit casts overloaded manually', ` struct A() impl A { fun as(value: A): i32 = 1 } impl A { fun as(value: A): boolean = true } impl A { #[explicit] fun as(value: A): f32 = 3.0 } #[export] fun test(): void = { support::test::assert(1 == A, "test implicit i32 cast") support::test::assert(true == A, "test implicit boolean cast 1") support::test::assert(A, "test implicit boolean cast 2") support::test::assert(A as f32 == 3.0, "test implicit f32 cast") } `, async x => { x.exports.test(); } ); }); describe('traits', () => { test( 'Self\'s discriminant should be equal to Type\'s discriminant', ` trait Checkable { fun check(): u32 fun check2(): u32 } struct A() struct B() impl Checkable for A { fun check(): u32 = Self.^discriminant fun check2(): u32 = A.^discriminant } impl Checkable for B { fun check(): u32 = Self.^discriminant fun check2(): u32 = B.^discriminant } #[export] fun A1(): u32 = A.check() #[export] fun A2(): u32 = A.check2() #[export] fun B1(): u32 = B.check() #[export] fun B2(): u32 = B.check2() `, async x => { expect(x.exports.A1()).to.eq(x.exports.A2()); expect(x.exports.B1()).to.eq(x.exports.B2()); expect(x.exports.A1()).to.not.eq(x.exports.B1()); } ); test( 'concrete type must be assignable to Self in trait', ` trait Sumable { fun +(lhs: Self, rhs: Self): Self } struct A(num: f32) struct B(num: i32) impl Sumable for A { fun +(lhs: Self, rhs: A): A = A(lhs.num + rhs.num) } impl Sumable for B { fun +(lhs: B, rhs: Self): Self = B(lhs.num + rhs.num) } #[export] fun sumA(x: f32, y: f32): f32 = (A(x) + A(y)).num #[export] fun sumB(x: i32, y: i32): i32 = (B(x) + B(y)).num `, async x => { expect(x.exports.sumA(1.5, 2)).to.eq(3.5); expect(x.exports.sumB(1.1, 2.1)).to.eq(3); } ); }); describe('injected wasm', () => { test( 'x + 44', ` #[export] fun otherFunction(): i32 = 44 #[export] fun main(x: i32): i32 = %wasm { (i32.add (local.get $x) (call $otherFunction)) } `, async x => { expect(x.exports.main(1)).to.eq(45); expect(x.exports.main(2)).to.eq(46); } ); }); describe.skip('namespaces', () => { test( 'resolve variable declarations in namespaces', ` type A = %struct { } impl A { val x: boolean = true } #[export] fun main(): boolean = A.x `, async x => { expect(x.exports.main()).to.eq(1); } ); }); describe('numbers', () => { test( 'casts', ` import support::test #[export] fun i32f32(i: i32): f32 = i as f32 `, async (x, err) => { if (err) throw err; expect(x.exports.i32f32(44.9)).to.eq(44); } ); }); describe('methods getters setters', () => { test( 'methods', ` import support::test struct T() impl T { #[method] fun a(self: T): i32 = 1 #[method] fun a(self: T, a: i32): i32 = 2 #[method] fun a(self: T, a: boolean): i32 = 3 #[method] fun a(self: T, a: boolean, b: i32): i32 = 4 } #[export] fun a(): i32 = T().a() #[export] fun b(): i32 = T().a(1) #[export] fun c(): i32 = T().a(false) #[export] fun d(): i32 = T().a(false, 1) `, async (x, err) => { if (err) throw err; expect(x.exports.a()).to.eq(1); expect(x.exports.b()).to.eq(2); expect(x.exports.c()).to.eq(3); expect(x.exports.d()).to.eq(4); } ); test( 'methods, mutating', ` import support::test struct T(value: i32) impl T { #[method] fun reset(self: T): void = { self.value = 0 } #[method] fun next(self: T): i32 = { self.value = self.value + 1 self.value } } var t = T(0) #[export] fun next(): i32 = t.next() #[export] fun reset(): void = t.reset() `, async (x, err) => { if (err) throw err; expect(x.exports.next()).to.eq(1); expect(x.exports.next()).to.eq(2); expect(x.exports.next()).to.eq(3); expect(x.exports.next()).to.eq(4); x.exports.reset(); expect(x.exports.next()).to.eq(1); expect(x.exports.next()).to.eq(2); expect(x.exports.next()).to.eq(3); expect(x.exports.next()).to.eq(4); } ); test( 'index selector getter', ` import support::test struct T(value: i32) impl T { #[getter] fun [](self: T, index: i32): i32 = self.value * index #[getter] fun [](self: T, index: boolean): i32 = self.value } var t = T(123) #[export] fun mul(i: i32): i32 = t[i] #[export] fun bool(i: boolean): i32 = t[i] `, async (x, err) => { if (err) throw err; expect(x.exports.mul(123)).to.eq(123 * 123); expect(x.exports.bool(false)).to.eq(123); } ); }); describe('schemas', () => { test( 'discriminant', ` import support::test #[export] fun test1(): u32 = never.^discriminant `, async (x, err) => { if (err) throw err; expect(x.exports.test1()).to.be.gt(0); } ); test( 'sizes', ` struct Struct1() struct Struct2(a: u8) struct Struct3(a: u8, b: Struct2) enum List { Nil Cons(a: i64, b: List) } enum Color { None Red Green Blue Custom(hex: i32) } struct CatBag(a: i32, b: boolean, c: f32, d: i64, e: f64, f: Color, g: Red | None) #[export] fun int(): u32 = i32.^byteSize #[export] fun intAlloc(): u32 = i32.^allocationSize #[export] fun byte(): u32 = u8.^byteSize #[export] fun byteAlloc(): u32 = u8.^allocationSize #[export] fun struct1(): u32 = Struct1.^byteSize #[export] fun struct1Alloc(): u32 = Struct1.^allocationSize #[export] fun struct2(): u32 = Struct2.^byteSize #[export] fun struct2Alloc(): u32 = Struct2.^allocationSize #[export] fun struct3(): u32 = Struct3.^byteSize #[export] fun struct3Alloc(): u32 = Struct3.^allocationSize #[export] fun list(): u32 = List.^byteSize #[export] fun nil(): u32 = Nil.^byteSize #[export] fun nilAlloc(): u32 = Nil.^allocationSize #[export] fun cons(): u32 = Cons.^byteSize #[export] fun consAlloc(): u32 = Cons.^allocationSize #[export] fun catBagAlloc(): u32 = CatBag.^allocationSize #[export] fun catBagOffsets(i: i32): u32 = match i { case 0 -> CatBag.^property$0_offset case 1 -> CatBag.^property$1_offset case 2 -> CatBag.^property$2_offset case 3 -> CatBag.^property$3_offset case 4 -> CatBag.^property$4_offset case 5 -> CatBag.^property$5_offset case 6 -> CatBag.^property$6_offset else -> -1 as u32 } `, async (x, err) => { if (err) throw err; const results = [ [x.exports.int(), 4], [x.exports.intAlloc(), 4], [x.exports.byte(), 1], [x.exports.byteAlloc(), 1], [x.exports.struct1(), 8], [x.exports.struct1Alloc(), 0], [x.exports.struct2(), 8], [x.exports.struct2Alloc(), 1], [x.exports.struct3(), 8], [x.exports.struct3Alloc(), 9], [x.exports.list(), 8], [x.exports.nil(), 8], [x.exports.nilAlloc(), 0], [x.exports.cons(), 8], [x.exports.consAlloc(), 16], [x.exports.catBagAlloc(), 41], [x.exports.catBagOffsets(0), 0], [x.exports.catBagOffsets(1), 4], [x.exports.catBagOffsets(2), 5], [x.exports.catBagOffsets(3), 9], [x.exports.catBagOffsets(4), 17], [x.exports.catBagOffsets(5), 25], [x.exports.catBagOffsets(6), 33] ]; expect(JSON.stringify(results.map($ => $[0]))).to.eq(JSON.stringify(results.map($ => $[1]))); } ); }); describe('loops', () => { test( 'loop one', ` #[export "sumTimes"] fun main(i: i32): i32 = { var current = i var ret = 0 loop { ret = ret + 1 if (1 == 1){ current = current - 1 if (current == 0) break else continue } panic() } ret } `, async (x, err) => { if (err) throw err; expect(x.exports.sumTimes(10)).to.eq(10); } ); }); describe('strings', () => { test( 'strings in different memory locations are equal', ` var a = "asd" var b = "asd" var c = "xxx" #[export] fun test(): void = { var x = "a" ++ "s" ++ "d" support::test::assert(a == b, "a == b") support::test::assert(b == b, "b == b") support::test::assert(b == a, "b == a") support::test::assert(b != c, "b != c") support::test::assert(a != c, "a != c") support::test::assert(a == x, "a == x") support::test::assert(b == x, "b == x") support::test::assert(c != x, "c != x") support::test::assert(x == a, "x == a") support::test::assert(x == b, "x == b") support::test::assert(x != c, "x != c") support::test::assert(a as ref != b as ref, "a as ref != b as ref") support::test::assert(b as ref == b as ref, "b as ref == b as ref") support::test::assert(a as ref == a as ref, "a as ref == a as ref") support::test::assert(b as ref != a as ref, "b as ref != a as ref") support::test::assert(b as ref != c as ref, "b as ref != c as ref") support::test::assert(a as ref != c as ref, "a as ref != c as ref") support::test::assert(x as ref != a as ref, "x as ref != a as ref") support::test::assert(x as ref != b as ref, "x as ref != b as ref") support::test::assert(x as ref != c as ref, "x as ref != c as ref") } `, async (x, err) => { if (err) throw err; x.exports.test(); } ); test( 'str len', ` #[export] fun len(): u32 = "asd".length #[export] fun b(x: i32): u32 = match x { case 0 -> "".length case 1 -> "1".length case 2 -> "11".length case 3 -> "⨔⨔⨔".length else -> { panic() 0 as u32 } } `, async (x, err) => { if (err) throw err; expect(x.exports.len()).to.eq(3); expect(x.exports.b(0)).to.eq(0); expect(x.exports.b(1)).to.eq(1); expect(x.exports.b(2)).to.eq(2); expect(x.exports.b(3)).to.eq(3); expect(() => x.exports.b(92)).to.throw(); } ); test( 'String.charAt', ` val str = "asd❮𝐑" #[export] fun charAt(at: u32): u16 = str[at] #[export] fun len(): u32 = str.length `, async (x, err) => { if (err) throw err; expect(x.exports.len()).to.eq(6); let str = String.fromCodePoint(...[0, 1, 2, 3, 4, 5].map($ => x.exports.charAt($))); expect(str).to.eq('asd❮𝐑'); expect(() => x.exports.charAt(100)).to.throw(); } ); test( 'keccak', ` import system::hash::keccak var k = Keccak() #[export] fun resultAddress(): u32 = { k.result.ptr - 4 as u32 } #[export] fun reset(): void = { Keccak.reset(k) } #[export] fun digest(): u32 = { Keccak.digest(k).ptr } #[export] fun update(address: u32, length: u32): void = { Keccak.update(k, address, length) } #[export] fun topMemory(): u32 = { system::core::memory::getMaxMemory() } `, async (x, err) => { if (err) throw err; const dataView = new DataView(x.exports.memory.buffer); const update = (data: string) => { const safeOffset = x.exports.topMemory(0); const bytes = getBytes(data); bytes.forEach((value: number, ix: number) => { dataView.setUint8(safeOffset + ix, value); }); x.exports.update(safeOffset, bytes.length); }; const getResult = (finalize = true) => { if (finalize) { x.exports.digest(); } const retAddress = x.exports.resultAddress(0); expect(retAddress).to.gt(0, 'retAddress must be > 0'); return readBytes(x.exports.memory.buffer, retAddress) .map($ => ('00' + $.toString(16)).substr(-2)) .join(''); }; const bytes = getResult(); expect(bytes.length).to.eq(64); expect(bytes).to.eq('c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'); const testStr = (data: string, hash: string) => { x.exports.reset(); update(data); const result = getResult(true); expect(result).to.eq(hash, `hash of ${JSON.stringify(data)}`); }; // test asd testStr('asd', '87c2d362de99f75a4f2755cdaaad2d11bf6cc65dc71356593c445535ff28f43d'); // test again to verify we do not let any trash behind testStr('asd', '87c2d362de99f75a4f2755cdaaad2d11bf6cc65dc71356593c445535ff28f43d'); testStr( ';lkja;slkdjfa;sdflasldfhaisdfiahlisdfhliasdfhasdhklfaklsdfjkashldf😂🤯🤬😱😨😥', 'f4cf631d11ba45c1f26071907fd75542494e6a01c24fcae7666422afe1f5ddb8' ); testStr('➙➛➪➸⤃⇏➳⇛⤙⤞⥇', 'ce14f15b91fe58c714ac1ce02497ea2d18d043cab566bb0425ed59531728c4f1'); } ); }); describe('type alias', () => { test( 'type alias of native', ` type int = i32 type Integer = int #[export] fun add(a: i32, b: int): int = a + b #[export] fun add2(a: i32, b: int): Integer = a + b `, async (x, err) => { if (err) throw err; expect(x.exports.add(10, 13)).to.eq(23); expect(x.exports.add2(30, 13)).to.eq(43); } ); test( 'alias discriminants', ` type newKindOfString = ref #[export] fun d_ref(): u32 = newKindOfString.^discriminant #[export] fun d_str(): u32 = ref.^discriminant `, async (x, err) => { if (err) throw err; const d_ref = x.exports.d_ref(); const d_str = x.exports.d_str(); expect(d_ref).to.gt(0); expect(d_str).to.gt(0); expect(d_str).to.not.eq(d_ref); } ); }); describe('struct', () => { test( 'get struct values', ` struct Vector3(x: i32, y: i32, z: i32) #[export] fun testPassing(): void = { var a = Vector3(1, 2, 3) support::test::verify( a is Vector3, "a is Vector3" ) support::test::mustEqual( Vector3.x(a), 1, "x") support::test::mustEqual( Vector3.y(a), 2, "y" ) support::test::mustEqual( Vector3.z(a), 3, "z" ) } #[export] fun testFailing(): void = { var a = Vector3(1, 2, 3) support::test::assert( Vector3.x(a) == 999, "this one must fail" ) } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); expect(() => x.exports.testFailing()).to.throw(); } ); test( 'set struct values', ` enum Color { None Red Green Blue Custom(hex: i32) } struct CatBag(a: i32, b: boolean, c: f32, d: i64, e: f64, f: Color, g: Red | None) #[export] fun testPassing(): void = { var a = CatBag(1, true, 3.0, 0x8 as i64, 0.4 as f64, Red, Red) support::test::assert( a is CatBag ) support::test::assert( CatBag.a(a) == 1 ) support::test::assert( CatBag.b(a) == true ) support::test::assert( CatBag.c(a) == 3.0 ) support::test::assert( CatBag.d(a) == 0x8 ) support::test::assert( CatBag.e(a) == 0.4 as f64 ) support::test::assert( CatBag.f(a) is Red ) support::test::assert( CatBag.g(a) is Red ) support::test::assert( CatBag.f(a) is Color ) support::test::assert( CatBag.g(a) is Color ) CatBag.a(a, 5) CatBag.b(a, false) CatBag.c(a, -999.0) CatBag.d(a, 0xdeadbeef as i64) CatBag.e(a, 6.08e23 as f64) CatBag.f(a, Custom(333)) CatBag.g(a, None) support::test::assert( CatBag.a(a) == 5 ) support::test::assert( CatBag.b(a) == false ) support::test::assert( CatBag.c(a) == -999.0 ) support::test::assert( CatBag.d(a) == 0xdeadbeef as i64 ) support::test::assert( CatBag.e(a) == 6.08e23 as f64 ) support::test::assert( CatBag.f(a) is Custom ) support::test::assert( CatBag.g(a) is None ) support::test::assert( CatBag.f(a) is Color ) support::test::assert( CatBag.g(a) is Color ) var custom = CatBag.f(a) support::test::assert( custom is Custom ) match custom { case x is Custom -> support::test::assert( Custom.hex(x) == 333 ) else -> panic() } } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); } ); test( 'chained getters', ` enum Tree { Leaf(value: i32) Branch(left: Leaf) } #[export] fun testPassing(): void = { var a = Branch(Leaf(1)) support::test::assert( a is Branch ) support::test::assert( a.left is Leaf ) support::test::assert( a.left.value == 1 ) a.left.value = 2 support::test::assert( a.left.value == 2 ) } #[export] fun testFailing(): void = { var a = Branch(Leaf(1)) a.left.value = 2 support::test::assert( a.left.value == 1, "this one MUST fail" ) } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); expect(() => x.exports.testFailing()).to.throw(); } ); test( 'set struct values with getters and setters', ` enum Color { None Red Green Blue Custom(hex: i32) } struct CatBag(a: i32, b: boolean, c: f32, d: i64, e: f64, f: Color, g: Red | None) #[export] fun testPassing(): void = { var a = CatBag(1, true, 3.0, 0x8 as i64, 0.4 as f64, Red, Red) support::test::assert( a is CatBag, "A" ) support::test::assert( a.a == 1, "B" ) support::test::assert( a.b == true, "C" ) support::test::assert( a.c == 3.0, "D" ) support::test::assert( a.d == 0x8, "E" ) support::test::assert( a.e == 0.4 as f64, "F" ) support::test::assert( a.f is Red, "G" ) support::test::assert( a.g is Red, "H" ) support::test::assert( a.f is Color, "I" ) support::test::assert( a.g is Color, "J" ) a.a = 5 a.b = false a.c = -999.0 a.d = 0xdeadbeef as i64 a.e = 6.08e23 as f64 support::test::printNumber(a.c) a.f = Custom(333) support::test::printNumber(a.c) a.g = None support::test::printNumber(0) support::test::printNumber(a.a) support::test::assert( a.a == 5, "K" ) support::test::printNumber( if(a.b) 1 else 0 ) support::test::assert( a.b == false, "L" ) support::test::printNumber(a.c) support::test::assert( a.c == -999.0, "M" ) support::test::assert( a.d == 0xdeadbeef as i64, "N" ) support::test::assert( a.e == 6.08e23 as f64, "Ñ" ) support::test::assert( a.f is Custom, "O" ) support::test::assert( a.g is None, "P" ) support::test::assert( a.f is Color, "Q" ) support::test::assert( a.g is Color, "V" ) support::test::assert( a.f is Custom, "W" ) match a.f { case x is Custom -> support::test::assert( x.hex == 333, "X" ) else -> support::test::assert( false, "Y" ) } } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); } ); test( 'varidic n-ary and pattern matching', ` enum Enum { None Custom(hex: i32) } #[export] fun testPassing(): void = { var custom: Enum = Custom(333) match custom { case x is Custom -> support::test::assert( x.hex == 333 ) else -> panic() } } #[export] fun testFailing(): void = { var custom: Enum = None match custom { case x is Custom -> support::test::assert( Custom.hex(x) == 333 ) else -> panic() } } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); expect(() => x.exports.testFailing()).to.throw(); } ); test( 'automatic coercion in binary operations', ` import support::test var a64 = 123 as i64 var a32 = 123 as i32 var a16 = 123 as i16 var a8 = 123 as u8 var b64 = 99 as i64 var b32 = 99 as i32 var b16 = 99 as i16 var b8 = 99 as u8 #[export] fun testPassing(): void = { assert( a64 == a32, "a64 == a32" ) assert( a64 == a16, "a64 == a16" ) assert( a64 == a8, "a64 == a8" ) assert( a64 == a64, "a64 == a64" ) assert( a64 != b32, "a64 != b32" ) assert( a64 != b16, "a64 != b16" ) assert( a64 != b8, "a64 != b8" ) assert( a64 != b64, "a64 != b64" ) } `, async (x, err) => { if (err) throw err; x.exports.testPassing(); } ); // test( // 'automatic coercion in binary operations, automatic cast by declaration', // ` // import support::test // var a64: i64 = 123 // var a32: i32 = 123 // var a16: i16 = 123 // var a8: u8 = 123 // var b64: i64 = 99 // var b32: i32 = 99 // var b16: i16 = 99 // var b8: u8 = 99 // #[export] fun testPassing(): void = { // assert( a64 == a32, "a64 == a32" ) // assert( a64 == a16, "a64 == a16" ) // assert( a64 == a8, "a64 == a8" ) // assert( a64 == a64, "a64 == a64" ) // assert( a64 != b32, "a64 != b32" ) // assert( a64 != b16, "a64 != b16" ) // assert( a64 != b8, "a64 != b8" ) // assert( a64 != b64, "a64 != b64" ) // } // `, // async (x, err) => { // if (err) throw err; // x.exports.testPassing(); // } // ); test( 'store values', ` struct Custom(r: i32, g: i32) val x = Custom(0,0) val y = Custom(0,0) fun getX(): u32 = addressFromRef(x) fun getY(): u32 = addressFromRef(y) #[export] fun testLoad(): void = { support::test::assert(i32.load(x) == 0, "i32.load(x) == 0") support::test::assert(i32.load(y) == 0, "i32.load(y) == 0") } #[export] fun testStore(): void = { i32.store(x, 3) i32.store(y, 2882400001) // 0xabcdef01 i32.store(y, 5, 5 as u32) } #[export] fun assert(): void = { support::test::assert(i32.load(x) == 3, "i32.load(x) == 3") support::test::assert(i32.load(y) as u32 == 0xABCDEF01, "i32.load(y) as u32 == 0xABCDEF01") support::test::assert(i32.load(y) == 0xABCDEF01 as i32, "i32.load(y) == 0xABCDEF01 as i32") support::test::assert(i32.load(y) as i64 == 0xABCDEF01 as i32 as i64, "i32.load(y) as i64 == 0xABCDEF01 as i64") support::test::assert(u8.load(y) as i32 == 0x01 as i32, "u8.load(y) as i32 == 0x01 as i32") support::test::assert(u8.load(y, 5 as u32) as i32 == 5, "u8.load(y, 5 as u32) as i32 == 5") } `, async (x, err) => { if (err) throw err; x.exports.testLoad(); x.exports.testStore(); x.exports.assert(); } ); test( 'store values 2', ` enum x { Custom(r: i32, g: i32) } #[export] fun testColors(): void = { val x = Custom(0,0) val y = Custom(0,0) support::test::assert(i32.load(x) == 0) support::test::assert(i32.load(y) == 0) i32.store(x, 3) i32.store(y, 2882400001) // 0xabcdef01 i32.store(y, 5, 5 as u32) support::test::assert(i32.load(x) == 3) support::test::assert(i32.load(y) == 0xABCDEF01 as i32) support::test::assert(u8.load(y) as i32 == 0x01 as i32) support::test::assert(u8.load(y, 5 as u32) as i32 == 5) } #[export] fun retRef(): u32 = addressFromRef(Custom(0, 0)) `, async (x, err) => { if (err) throw err; x.exports.testColors(); const a = x.exports.retRef(); const b = x.exports.retRef(); const c = x.exports.retRef(); expect(b).to.gt(a); expect(c).to.gt(b); } ); }); describe('operators', () => { test( 'single addition, overrides core', ` type i32 = %stack { lowLevelType="i32" byteSize=4 } type f32 = %stack { lowLevelType="f32" byteSize=4 } impl f32 { fun +(a: f32, b: i32): i32 = 0 } impl i32 { fun +(a: i32, b: i32): i32 = 1 fun +(a: i32, b: f32): i32 = 4 } #[export] fun main1(a: i32, b: f32): i32 = { a + b } #[export] fun main2(a: i32, b: f32): i32 = { b + a } #[export] fun main3(a: i32, b: i32): i32 = { b + a } `, async x => { expect(x.exports.main1(1, 1.0)).to.eq(4); expect(x.exports.main2(1, 1.0)).to.eq(0); expect(x.exports.main3(1, 1)).to.eq(1); } ); test( 'operators', ` #[export] fun main(a: i32, b: i32): i32 = { a + b } `, async x => { expect(x.exports.main(1, 1)).to.eq(2); } ); }); describe('return types', () => { test( 'void return', ` type void = %injected #[export] fun main(): void = { // stub } `, async x => { expect(x.exports.main()).to.eq(undefined); } ); test( 'void return 2', ` type void = %injected #[export] fun main(): void = {} `, async x => { expect(x.exports.main()).to.eq(undefined); } ); }); describe('imports', () => { test( 'panic', ` #[export] fun test(): void = { support::test::assert((1 > 0) == true, "(1 > 0) == true") support::test::assert((0 > 0) == false, "(0 > 0) == false") support::test::assert((0 > 1) == false, "(0 > 1) == false") support::test::assert((0 >= 0) == true, "(0 >= 0) == true") support::test::assert((1 < 0) == false, "(1 < 0) == false") support::test::assert((0 < 0) == false, "(0 < 0) == false") support::test::assert((0 < 1) == true, "(0 < 1) == true") support::test::assert((0 <= 1) == true, "(0 <= 1) == true") } #[export] fun testBool(i: i32): boolean = match i { case 0 -> testBool0() case 1 -> testBool1() case 2 -> testBool2() case 3 -> testBool3() case 4 -> testBool4() case 5 -> testBool5() case 6 -> testBool6() case 7 -> testBool7() case 8 -> testBool8() case 9 -> testBool9() case 10 -> testBool10() case 11 -> testBool11() case 12 -> testBool12() else -> testBool99() } #[export] fun testBool0(): boolean = 1 > 0 // true #[export] fun testBool1(): boolean = 0 > 0 // false #[export] fun testBool2(): boolean = 0 > 1 // false #[export] fun testBool3(): boolean = 1 >= 0 // true #[export] fun testBool4(): boolean = 0 >= 0 // true #[export] fun testBool5(): boolean = 0 >= 1 // false #[export] fun testBool6(): boolean = 1 < 0 // false #[export] fun testBool7(): boolean = 0 < 0 // false #[export] fun testBool8(): boolean = 0 < 1 // true #[export] fun testBool9(): boolean = 1 <= 0 // false #[export] fun testBool10(): boolean = 0 <= 0 // true #[export] fun testBool11(): boolean = 0 <= 1 // true #[export] fun testBool12(): boolean = false // false #[export] fun testBool99(): boolean = true // true #[export] fun testPanic1(): void = { support::test::assert((0 > 0) == true, "this one MUST fail") } #[export] fun testPanic2(): void = { support::test::assert(0 > 0, "this one MUST fail") } `, async x => { x.exports.test(); expect( [ !!x.exports.testBool0(), !!x.exports.testBool1(), !!x.exports.testBool2(), !!x.exports.testBool3(), !!x.exports.testBool4(), !!x.exports.testBool5(), !!x.exports.testBool6(), !!x.exports.testBool7(), !!x.exports.testBool8(), !!x.exports.testBool9(), !!x.exports.testBool10(), !!x.exports.testBool11(), !!x.exports.testBool12(), !!x.exports.testBool99() ].map(($, $$) => `fn ${$$} -> ${$}`), 'fn compare' ).to.deep.eq( [true, false, false, true, true, false, false, false, true, false, true, true, false, true].map( ($, $$) => `fn ${$$} -> ${$}` ) ); expect( [ x.exports.testBool(0), x.exports.testBool(1), x.exports.testBool(2), x.exports.testBool(3), x.exports.testBool(4), x.exports.testBool(5), x.exports.testBool(6), x.exports.testBool(7), x.exports.testBool(8), x.exports.testBool(9), x.exports.testBool(10), x.exports.testBool(11), x.exports.testBool(12), x.exports.testBool(99) ].map(($, $$) => `${$$} -> ${$}`), 'match compare' ).to.deep.eq([1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1].map(($, $$) => `${$$} -> ${$}`)); expect(() => x.exports.testPanic1(), 'testPanic1').to.throw(); expect(() => x.exports.testPanic2(), 'testPanic2').to.throw(); } ); }); describe('mutability', () => { test( 'mutable global', ` type void = %injected val bc = 1 var a: i32 = { bc - 2 } #[export] fun retMinusOne(): i32 = 0 - 1 #[export] fun main(x: i32): void = { if (x < 0) { a = 0 } else { a = x } } #[export] fun getValue(): i32 = a `, async x => { expect(x.exports.getValue()).to.eq(-1); expect(x.exports.main(1)).to.eq(undefined); expect(x.exports.getValue()).to.eq(1); expect(x.exports.main(3)).to.eq(undefined); expect(x.exports.getValue()).to.eq(3); expect(x.exports.main(-3)).to.eq(undefined); expect(x.exports.getValue()).to.eq(0); expect(x.exports.main(30)).to.eq(undefined); expect(x.exports.getValue()).to.eq(30); } ); test( 'void return', ` #[export] fun main(x: i32): i32 = { var a: i32 = 1 if (x == 1) { a = 3 } else {} a } `, async x => { expect(x.exports.main(1)).to.eq(3); expect(x.exports.main(3)).to.eq(1); } ); test( 'void return, if w/o else', ` #[export] fun main(x: i32): i32 = { var a: i32 = 1 if (x == 1) { a = 3 } a } `, async x => { expect(x.exports.main(1)).to.eq(3); expect(x.exports.main(3)).to.eq(1); } ); test( 'void return, if w/o else w/o types', ` #[export] fun main(x: i32): i32 = { var a = 1 if (x == 1) { a = 3 } a } `, async x => { expect(x.exports.main(1)).to.eq(3); expect(x.exports.main(3)).to.eq(1); } ); }); describe('math', () => { test( 'sum', ` #[export] fun add(a: i32, b: i32): i32 = a + b #[export] fun add2(a: f32, b: f32): f32 = { a + b } `, async x => { expect(x.exports.add(1, 2)).to.eq(3); expect(x.exports.add(-1, 2)).to.eq(1); expect(x.exports.add2(1, 2)).to.eq(3); expect(x.exports.add2(0.2, 0.3)).to.eq(0.5); expect(x.exports.add2(-1, 2)).to.eq(1); } ); test( 'sum 2', ` #[export] fun add(a: i32, b: i32): i32 = {{{a}} + {{{b}}}} #[export] fun add2(a: f32, b: f32): f32 = {{ {a} + {b} }} `, async x => { expect(x.exports.add(1, 2)).to.eq(3); expect(x.exports.add(-1, 2)).to.eq(1); expect(x.exports.add2(1, 2)).to.eq(3); expect(x.exports.add2(0.2, 0.3)).to.eq(0.5); expect(x.exports.add2(-1, 2)).to.eq(1); } ); test( 'overload infix', ` private fun sum(a: f32, b: f32): f32 = a + b private fun sum(a: i32, b: i32): i32 = a + b private fun sum(a: i32): i32 = a + 100 private fun sum(a: f32): f32 = a + 100.0 #[export] fun testInt(a: i32, b: i32): i32 = sum(a,b) #[export] fun testFloat(a: f32, b: f32): f32 = sum(a,b) #[export] fun testInt2(a: i32): i32 = sum(a) #[export] fun testFloat2(a: f32): f32 = sum(a) `, async x => { expect(x.exports.testInt(46, 3)).to.eq(49); expect(x.exports.testFloat(0.2, 0.3)).to.eq(0.5); expect(x.exports.testInt2(46)).to.eq(146); expect(x.exports.testFloat2(0.5)).to.eq(100.5); } ); test( 'pattern matching 1', ` #[export] fun test1(a: i32): boolean = match a { case 1 -> true else -> false } #[export] fun test2(a: i32): i32 = match a { case 10 -> 1 case 20 -> 2 case 30 -> 3 case 40 -> 4 case 50 -> 5 case 60 -> 6 case 70 -> 7 case 80 -> 8 case 90 -> 9 else -> 0 } #[export] fun test3(a: i32): boolean = match (a + 1) { case 1 -> true else -> false } `, async x => { expect(x.exports.test1(1)).to.eq(1); expect(x.exports.test1(0)).to.eq(0); expect(x.exports.test2(10)).to.eq(1); expect(x.exports.test2(20)).to.eq(2); expect(x.exports.test2(30)).to.eq(3); expect(x.exports.test2(40)).to.eq(4); expect(x.exports.test2(50)).to.eq(5); expect(x.exports.test2(60)).to.eq(6); expect(x.exports.test2(70)).to.eq(7); expect(x.exports.test2(80)).to.eq(8); expect(x.exports.test2(90)).to.eq(9); expect(x.exports.test2(700)).to.eq(0); expect(x.exports.test2(71)).to.eq(0); expect(x.exports.test2(-170)).to.eq(0); expect(x.exports.test2(0)).to.eq(0); expect(x.exports.test3(0)).to.eq(1); expect(x.exports.test3(-1)).to.eq(0); } ); }); describe('fixtures/execution', () => { testFolder('/**/*.lys'); }); describe('fixtures/execution/modules', () => { testFolder('/modules/*.md'); }); });
the_stack
import {h} from 'maquette'; import { Log } from "../common/log" import * as Langs from '../definitions/languages'; import * as Graph from '../definitions/graph'; import * as Values from '../definitions/values'; import {createOutputPreview, createMonacoEditor} from '../editors/editor'; import {Md5} from 'ts-md5'; import axios from 'axios'; import {AsyncLazy} from '../common/lazy'; import * as Doc from '../services/documentService'; // ------------------------------------------------------------------------------------------------ // Helper functions for working with data store // ------------------------------------------------------------------------------------------------ interface Script { src:string; text: string; } interface HtmlElements { scripts: Array<Script>, html: string, css: string } async function getValue(blob, preview:boolean, datastoreURI:string) : Promise<any> { var pathname = new URL(blob).pathname; let headers = {'Accept': 'application/json'} let url = datastoreURI.concat(pathname) if (preview) url = url.concat("?nrow=10") try { let response = await axios.get(url, {headers: headers}); return response.data } catch (error) { throw error; } } async function getCachedOrEval(serviceUrl, body, datastoreURI) : Promise<any> { let cacheUrl = datastoreURI.concat("/" + body.hash).concat("/.cached") try { let params = {headers: {'Accept': 'application/json'}} Log.trace("external", "Checking cached response: %s", cacheUrl) let response = await axios.get(cacheUrl, params) return response.data } catch(e) { Log.trace("external", "Checking failed at external, calling eval (%s)", e) let params = { headers: {'Content-Type': 'application/json'} } let result = await axios.post(serviceUrl.concat("/eval"), body, params) await axios.put(cacheUrl, result.data, params) return result.data } } function parseHTML(htmlResponse:string):HtmlElements { let inlineScriptHeader = "<script type=\"text/javascript\">" let scriptEnder = "</script>" function parseScript():Array<Script>{ let dom = new DOMParser() let doc = dom.parseFromString(htmlResponse, 'text/html') let scriptElements:HTMLCollectionOf<HTMLScriptElement> = doc.scripts let scripts:Script[] = [] for (let s = 0; s < scriptElements.length; s++) { let src:string = scriptElements[s].src==null?"":scriptElements[s].src let text:string = scriptElements[s].text==null?"":scriptElements[s].text scripts.push({src:src, text:text}) } return scripts } // function parseScript(htmlResponse:string):string { // if (htmlResponse.indexOf(inlineScriptHeader) > -1) // return htmlResponse.substring(htmlResponse.indexOf(inlineScriptHeader)+inlineScriptHeader.length, htmlResponse.indexOf(scriptEnder)) // else // return "" // } function parseElements():string { if (htmlResponse.indexOf(inlineScriptHeader) > -1) { let beforeInlineScript:string = htmlResponse.substring(0,htmlResponse.indexOf(inlineScriptHeader)) let afterInlineScript:string = htmlResponse.substring(htmlResponse.indexOf(scriptEnder)+scriptEnder.length) return beforeInlineScript.concat(afterInlineScript) } else return htmlResponse } return {scripts:parseScript(), html: parseElements(), css:""} } function evalAndLoadInlineScript(aScript:Script) { if (aScript.text.length > 0) { eval(aScript.text); var scr = document.createElement("script"); scr.innerHTML = aScript.text; document.head.appendChild(scr); } if (aScript.src.length > 0) { var scr = document.createElement("script"); scr.setAttribute("src", aScript.src); document.head.appendChild(scr); } } async function getEval(body, serviceURI, datastoreURI) : Promise<Langs.EvaluationResult> { try { let response = await getCachedOrEval(serviceURI, body, datastoreURI); var results : Values.ExportsValue = { kind:"exports", exports:{} } if (response.output.toString().length > 0){ let printouts : Values.Printout = { kind:"printout", data:response.output.toString() } results.exports['console'] = printouts } for(let df of response.frames) { let exp : Values.DataFrame = { kind:"dataframe", url:<string>df.url, preview: await getValue(df.url, true, datastoreURI), // TODO: Just first X rows data: new AsyncLazy<any>(() => getValue(df.url,false,datastoreURI)) // TODO: This function is called later when JS calls data.getValue() }; if (Array.isArray(exp.preview)) results.exports[df.name] = exp } let figureIndex = 0; for(let df of response.figures) { let raw = await getValue(df.url,false,datastoreURI) let exp : Values.Figure = {kind:"figure", data: raw[0]['IMAGE']}; results.exports['figure'+figureIndex.toString()] = exp figureIndex++; } if (response['html']) if (JSON.stringify(response.html) != "{}"){ let parsed:HtmlElements = parseHTML(response.html.toString()) var output : ((id:string) => void) = function(f) { let element:HTMLElement|null= document.getElementById(f) if (element){ element.innerHTML = parsed.html for (let s = 0; s < parsed.scripts.length; s++) { let img:HTMLImageElement = document.createElement('img') img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" img.onload = function(){evalAndLoadInlineScript(parsed.scripts[s])} element.appendChild(img) } } }; var exp : Values.JavaScriptOutputValue = { kind:"jsoutput", render: output } results.exports["output"] = exp } let evalResults:Langs.EvaluationResult = {kind: 'success', value: results} return evalResults; } catch (error) { if (error.response != null) { let e = {message:<string>error.response.data.error} let evalResults:Langs.EvaluationResult = {kind: 'error', errors: [e]} return evalResults } else { let e = {message:'Failed to evaluate'} let evalResults:Langs.EvaluationResult = {kind: 'error', errors: [e]} return evalResults } } } // ------------------------------------------------------------------------------------------------ // External language (eg. Python, R) plugin // ------------------------------------------------------------------------------------------------ /// A class that represents an external block. All blocks need to have /// `language` and "external" also keeps the source we edit and render export class ExternalBlockKind implements Langs.Block { language : string; source : string; constructor(source:string, language: string) { this.language = language; this.source = source; } } export interface ExternalSwitchTabEvent { kind: "switchtab" index: number } export type ExternalEvent = ExternalSwitchTabEvent export type ExternalState = { id: number block: ExternalBlockKind tabID: number } export const ExternalEditor : Langs.Editor<ExternalState, ExternalEvent> = { initialize: (id:number, block:Langs.Block) => { return { id: id, block: <ExternalBlockKind>block, tabID: 0} }, update: (state:ExternalState, event:ExternalEvent) => { switch(event.kind) { case 'switchtab': { return { id: state.id, block: state.block, tabID: event.index } } } return state }, render: (cell: Langs.BlockState, state:ExternalState, context:Langs.EditorContext<ExternalEvent>) => { let previewButton = h('button', { class:'preview-button', onclick:() => { Log.trace("editor", "Evaluate button clicked in external language plugin") context.evaluate(cell.editor.id) } }, ["Evaluate!"] ) let spinner = h('i', {id:'cellSpinner_'+cell.editor.id, class: 'fa fa-spinner fa-spin' }, []) let triggerSelect = (t:number) => context.trigger({kind:'switchtab', index: t}) let preview = h('div', {class:'preview'}, [(cell.code.value==undefined) ? (cell.evaluationState=='pending')?spinner:previewButton : (createOutputPreview(cell, triggerSelect, state.tabID, <Values.ExportsValue>cell.code.value))]); Log.trace("render", "Source as passed to editor to render: %s", JSON.stringify(state.block.source)) let code = createMonacoEditor(cell.code.language, state.block.source, cell, context) let errors = h('div', {}, [(cell.code.errors.length == 0) ? "" : cell.code.errors.map(err => {return h('p',{}, [err.message])})]) let rendered = h('div', {key:"rendered_".concat(cell.editor.id.toString())}, [code, (cell.code.errors.length >0)?errors:preview]) return rendered } } export class ExternalLanguagePlugin implements Langs.LanguagePlugin { readonly language: string; readonly iconClassName: string; readonly editor: Langs.Editor<ExternalState, ExternalEvent>; readonly serviceURI: string; readonly defaultCode : string; readonly regex_global:RegExp = /^%global/; readonly regex_local:RegExp = /^%local/; readonly datastoreURI: string; constructor(l: string, icon:string, serviceURI: string, code:string, datastoreUri: string) { this.language = l; this.iconClassName = icon; this.serviceURI = serviceURI; this.editor = ExternalEditor; this.defaultCode = code; this.datastoreURI = datastoreUri } getDefaultCode(id:number) { return this.defaultCode.replace(/\[ID\]/g, id.toString()); } async evaluate(context:Langs.EvaluationContext, node:Graph.Node) : Promise<Langs.EvaluationResult> { let externalNode = <Graph.ExternalNode>node function findResourceURL(fileName): string { for (let f = 0; f < context.resources.length; f++) { if (context.resources[f].fileName==fileName) { return context.resources[f].url } } return '' } switch(externalNode.kind) { case 'code': let importedFrames : { name:string, url:string }[] = []; let importedFiles : Array<string> = []; for (var ant of externalNode.antecedents) { let imported = <Graph.ExportNode>ant importedFrames.push({ name: imported.variableName, url: (<Values.DataFrame>imported.value).url }) } let src = externalNode.source.replace(/\r/g,'\n') let srcArray = src.split('\n') let strippedSrc = '' for (let l = 0; l < srcArray.length; l++) { if (srcArray[l].match(this.regex_local)) { let resourceName = srcArray[l].split(' ')[1] let resourceURL = findResourceURL(resourceName) if (resourceURL.length > 0){ importedFiles.push(resourceURL) } } else if (srcArray[l].match(this.regex_global)){ } else { strippedSrc = strippedSrc.concat(srcArray[l]).concat('\n') } } for (let r = 0; r < context.resources.length; r++) { if ((context.resources[r].scope == 'global')&&(context.resources[r].language == externalNode.language)) { let resourceURL = findResourceURL(context.resources[r].fileName) if (resourceURL.length > 0){ importedFiles.push(resourceURL) } } } let body = {"code": strippedSrc, "hash": externalNode.hash, "files" : importedFiles, "frames": importedFrames} return await getEval(body, this.serviceURI, this.datastoreURI); case 'export': let exportNode = <Graph.ExternalExportNode>node let exportNodeName = exportNode.variableName let exportsValue = <Values.ExportsValue>exportNode.code.value if (exportsValue==null) { if (exportNode.errors.length > 0) { return {kind: 'error', errors: exportNode.errors} } else { let errorMessage = "Fail to export".concat(exportNode.variableName); let graphError = {message: errorMessage} return {kind: 'error', errors: [graphError]} } } else { return {kind: 'success', value: exportsValue.exports[exportNodeName]} } } } parse (code:string) { return new ExternalBlockKind(code, this.language); } async bind (context:Langs.BindingContext, block: Langs.Block) : Promise<Langs.BindingResult> { let exBlock = <ExternalBlockKind>block let initialHash = Md5.hashStr(exBlock.source) let antecedents : Graph.Node[] = [] let newResources : Array<Langs.Resource> = [] function resourceExists(fileName):boolean{ for (let r = 0; r < context.resources.length; r++) { if (context.resources[r].fileName == fileName) return true } return false } async function putResource(fileName:string, code: string, datastoreURI:string) : Promise<string> { let hash = Md5.hashStr(fileName) try { let url = datastoreURI.concat("/"+hash).concat("/"+fileName) // let url = "http://wrattler_wrattler_data_store_1:7102" let headers = {'Content-Type': 'text/html'} var response = await axios.put(url, code, {headers: headers}); return url // return "http://wrattler_wrattler_data_store_1:7102".concat("/"+hash).concat("/"+variableName) } catch (error) { console.log(error) throw error; } } try { let url = this.serviceURI.concat("/exports") let src = exBlock.source.replace(/\r/g,'\n') let srcArray = src.split('\n') let strippedSrc = '' for (let l = 0; l < srcArray.length; l++) { if (srcArray[l].match(this.regex_global)){ let resourceName = srcArray[l].split(' ')[1] if (!resourceExists(resourceName)) { let response = await Doc.getResourceContent(context.resourceServerUrl, resourceName) let newResource:Langs.Resource = {fileName:resourceName, language:this.language, scope: 'global', url:await putResource(resourceName, response,this.datastoreURI)} newResources.push(newResource) } } else if (srcArray[l].match(this.regex_local)) { let resourceName = srcArray[l].split(' ')[1] if (!resourceExists(resourceName)) { let response = await Doc.getResourceContent(context.resourceServerUrl, resourceName) let newResource:Langs.Resource = {fileName:resourceName, language:this.language, scope: 'local', url:await putResource(resourceName, response,this.datastoreURI)} newResources.push(newResource) } } else { strippedSrc = strippedSrc.concat(srcArray[l]).concat('\n') } } let body = { "code": strippedSrc, "hash": initialHash, "frames": Object.keys(context.scope) } let headers = {'Content-Type': 'application/json'} let response = await axios.post(url, body, {headers: headers}) // .then(response=> { let namesOfImports:Array<string> = [] for (var n = 0 ; n < response.data.imports.length; n++) { if (namesOfImports.indexOf(response.data.imports[n]) < 0) { namesOfImports.push(response.data.imports[n]) if (response.data.imports[n] in context.scope) { let antecedentNode = context.scope[response.data.imports[n]] antecedents.push(antecedentNode); } } } let allHash = Md5.hashStr(antecedents.map(a => a.hash).join("-") + exBlock.source) let initialNode:Graph.ExternalCodeNode = { language:this.language, antecedents:antecedents, exportedVariables:[], kind: 'code', value: null, hash: <string>allHash, source: exBlock.source, errors: []} let cachedNode = <Graph.ExternalCodeNode>context.cache.tryFindNode(initialNode) let namesOfExports:Array<string> = [] let dependencies:Graph.ExternalExportNode[] = []; for (var n = 0 ; n < response.data.exports.length; n++) { if (namesOfExports.indexOf(response.data.exports[n]) < 0) { namesOfExports.push(response.data.exports[n]) let exportNode:Graph.ExternalExportNode = { variableName: response.data.exports[n], value: null, language:this.language, code: cachedNode, hash: <string>Md5.hashStr(allHash + response.data.exports[n]), kind: 'export', antecedents:[cachedNode], errors: [] }; let cachedExportNode = <Graph.ExternalExportNode>context.cache.tryFindNode(exportNode) dependencies.push(cachedExportNode) cachedNode.exportedVariables.push(cachedExportNode.variableName) } } Log.trace("binding", "Binding external - hash: %s, dependencies: %s", allHash, cachedNode.antecedents.map(n => n.hash)) return {code: cachedNode, exports: dependencies, resources:newResources}; } catch (error) { let newError:Graph.Error = {message:error.response.data.error} let code = { language:this.language, antecedents:antecedents, exportedVariables:[], kind: 'code', value: null, hash: <string>Md5.hashStr(exBlock.source), source: exBlock.source, errors: [newError]} return {code: code, exports: [], resources:[]}; } } save (block:Langs.Block) : string { let exBlock:ExternalBlockKind = <ExternalBlockKind> block let content:string = "" content = content .concat("```") .concat(exBlock.language) .concat("\n") .concat(exBlock.source) .concat("\n") .concat("```\n") return content } }
the_stack
import test from 'ava'; import { Context, TestContext } from 'ava'; import { IAddress, IDialogResult, IMessage, Message, Prompts, Session, UniversalBot } from 'botbuilder'; import { BotTester } from './../../src/BotTester'; import { IConfig } from './../../src/config'; import { TestConnector } from './../../src/TestConnector'; import { getAdaptiveCard, getAdaptiveCardAttachment, getAdaptiveCardMessage } from './../adaptiveCardProvider'; const connector = new TestConnector(); interface IBotTestContext { bot: UniversalBot; } //tslint:disable type AvaTestContext = TestContext & Context<any>; //tslint:enable interface IAvaBotTest extends AvaTestContext { context: IBotTestContext; } function getTestOptions(t: AvaTestContext): IConfig { return { assertionLibrary: 'ava', testContext: t }; } test.beforeEach((t: IAvaBotTest) => { t.context.bot = new UniversalBot(connector); }); test('it will fail if an incorrect response is returned', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello!'); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('Hola!', 'NOPE') .runTest()); }); test('will fail if one of multiple responses is incorrect', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello!'); session.send('how are you doing?'); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('Hola!', 'hello!', 'NOPE') .runTest() ); }); // refer to mocha notes for skip reason test.skip('it will fail if an empty collection is given', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello!'); }); try { new BotTester(bot, getTestOptions(t)).sendMessageToBot('Hola!', []); } catch (error) { t.true(error.Message.includes('expected response collections cannot be empty')); } }); test('Will fail if response is not in the random response collection', (t: IAvaBotTest) => { const bot = t.context.bot; const randomColors = ['red', 'green', 'blue', 'grey', 'gray', 'purple', 'magenta', 'cheese', 'orange', 'hazelnut']; bot.dialog('/', (session: Session) => { session.send(randomColors); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('tell me a color!', ['this', 'is', 'not', 'in', 'the', 'collection']) .runTest()); }); test('will fail if response to a prompt is not as expected', (t: IAvaBotTest) => { const bot = t.context.bot; //tslint:disable bot.dialog('/', [(session: Session) => { new Prompts.text(session, 'Hi there! Tell me something you like'); }, (session: Session, results: IDialogResult<string>) => { session.send(`${results.response} is pretty cool.`); new Prompts.text(session, 'Why do you like it?'); //tslint:enable }, (session: Session) => session.send('Interesting. Well, that\'s all I have for now')]); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('Hola!', 'Hi there! Tell me something you like') .sendMessageToBot('The sky', 'this is wrong') .sendMessageToBot('It\'s blue', 'Interesting. Well, that\'s all I have for now') .runTest() ); }); test('will fail if decorated messages do not match', (t: IAvaBotTest) => { const bot = t.context.bot; const customMessage: { someField?: {} } & IMessage = new Message() .text('this is text') .toMessage(); customMessage.someField = { a: 1 }; customMessage.type = 'newType'; const nonMatchingCustomMessage: { someField?: {} } & IMessage = new Message() .text('this is text') .toMessage(); nonMatchingCustomMessage.someField = 'nope'; nonMatchingCustomMessage.type = 'newType'; bot.dialog('/', (session: Session) => { session.send(customMessage); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('anything', nonMatchingCustomMessage) .runTest() ); }); const defaultAddress = { channelId: 'console', user: { id: 'user1', name: 'A' }, bot: { id: 'bot', name: 'Bot' }, conversation: { id: 'user1Conversation' } }; const user2Address = { channelId: 'console', user: { id: 'user2', name: 'B' }, bot: { id: 'bot', name: 'Bot' }, conversation: { id: 'user2Conversation' } }; function setupMultiUserAddressTest(bot: UniversalBot): void { bot.dialog('/', (session: Session) => session.send(session.message.address.user.name)); } test('incorrect address leads to failure, event with correct text', (t: IAvaBotTest) => { const bot = t.context.bot; setupMultiUserAddressTest(bot); const askForUser1Name = new Message() .text('What is my name?') .address(defaultAddress) .toMessage(); const expectedAddressInMessage = new Message() .address(user2Address) .toMessage(); const addr = { user: { id: 'user1' } } as IAddress; // partial addresses work as well (i.e. if you only want to check one field such as userId) const expectedPartialAddress = new Message() .address(addr) .toMessage(); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot(askForUser1Name, expectedAddressInMessage) .runTest() ); }); test('incorrect partial address leads to failure', (t: IAvaBotTest) => { const bot = t.context.bot; setupMultiUserAddressTest(bot); const askForUser1Name = new Message() .text('What is my name?') .address(defaultAddress) .toMessage(); const address = { user: { id: user2Address.user.id } } as IAddress; // partial addresses work as well (i.e. if you only want to check one field such as userId) const expectedPartialAddress = new Message() .address(address) .toMessage(); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot(askForUser1Name, expectedPartialAddress) .runTest() ); }); test('will fail if regex does not match', (t: IAvaBotTest) => { const bot = t.context.bot; const numberRegex = /^\d+/; bot.dialog('/', (session: Session) => { // send only numbers for this test case .... session.send(session.message.text); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('abcd', numberRegex) .runTest() ); }); test('can timeout', (t: IAvaBotTest) => { const timeout = 1000; const bot = t.context.bot; bot.dialog('/', (session: Session) => { // send only numbers for this test case .... setTimeout(() => session.send('hi there'), timeout * 2 ); }); return t.throws(new BotTester(bot, Object.assign({ timeout }, getTestOptions(t))) .sendMessageToBot('hey', 'hi there') .runTest()); }); test('will fail random order if response is not in collection', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hi'); session.send('there'); session.send('how are you?'); }); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBotIgnoringResponseOrder('anything', 'NOPE?', 'hi', 'there') .runTest()); }); test('will fail if a message filter is not correctly applied', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello'); session.send('how'); session.send('are'); session.send('you?'); }); const ignoreHowMessage = (message: IMessage) => !message.text.includes('how'); const ignoreAreMessage = (message: IMessage) => !message.text.includes('are'); return t.throws(new BotTester(bot, { messageFilters: [ignoreHowMessage, ignoreAreMessage]}) .sendMessageToBot('intro', 'hello', 'how', 'are', 'you?') .runTest()); }); test('will fail if a endOfConversationEvent is seen with an ingoreEndOfConversationEventFilter', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello'); session.endConversation(); }); return t.throws(new BotTester(bot, getTestOptions(t)) // need to timeout before the tests do to catch the error .setTimeout(500) .ignoreEndOfConversationEvent() //tslint:disable .sendMessageToBot('hey', 'hello', {type: 'endOfConversation'} as any) //tslint:enable .runTest()); }); test('will fail if a typing event is seen with an ignoreTypingEventFilter', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello'); session.sendTyping(); session.send('hey'); }); return t.throws(new BotTester(bot, getTestOptions(t)) // need to timeout before the tests do to catch the error .setTimeout(500) .ignoreTypingEvent() //tslint:disable .sendMessageToBot('hey', 'hello', {type: 'typing'} as any, 'hey') //tslint:enable .runTest()); }); test('will fail when there are no matching adaptive cards', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send(getAdaptiveCardMessage()); }); const card = getAdaptiveCard(); card.actions = [{title: 'this is not the correct title', type: 'this is no the correct type'}]; const message = getAdaptiveCardMessage(card); return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('anything', message) .runTest()); }); test('will fail when there are no attachments when they are expected', (t: IAvaBotTest) => { const bot = t.context.bot; bot.dialog('/', (session: Session) => { session.send('hello'); }); const expectedMessage = getAdaptiveCardMessage(); expectedMessage.text = 'hello'; return t.throws(new BotTester(bot, getTestOptions(t)) .sendMessageToBot('anything', expectedMessage) .runTest()); });
the_stack
import * as monaco from "monaco-editor"; import { Observable, Observer } from "rxjs"; import { first, map } from "rxjs/operators"; import { childOf, JupyterMessage, ofMessageType, Channels, } from "@nteract/messaging"; import { CompletionResults, CompletionMatch, completionRequest, js_idx_to_char_idx, } from "../editor-base"; /** * Jupyter to Monaco completion item kinds. */ const unknownJupyterKind = "<unknown>"; const jupyterToMonacoCompletionItemKind: { [key: string]: monaco.languages.CompletionItemKind; } = { [unknownJupyterKind]: monaco.languages.CompletionItemKind.Field, class: monaco.languages.CompletionItemKind.Class, function: monaco.languages.CompletionItemKind.Function, keyword: monaco.languages.CompletionItemKind.Keyword, instance: monaco.languages.CompletionItemKind.Variable, statement: monaco.languages.CompletionItemKind.Variable, }; /** * Completion item provider. */ class CompletionItemProvider implements monaco.languages.CompletionItemProvider { private channels: Channels | undefined; /** * Set Channels of Jupyter kernel. * @param channels Channels of Jupyter kernel. */ setChannels(channels: Channels | undefined) { this.channels = channels; } /** * Whether provider is connected to Jupyter kernel. */ get isConnectedToKernel() { return !!this.channels; } /** * Additional characters to trigger completion other than Ctrl+Space. */ get triggerCharacters() { return [" ", "<", "/", ".", "="]; } /** * Get list of completion items at position of cursor. * @param model Monaco editor text model. * @param position Position of cursor. */ async provideCompletionItems( model: monaco.editor.ITextModel, position: monaco.Position ) { // Convert to zero-based index let cursorPos = model.getOffsetAt(position); const code = model.getValue(); cursorPos = js_idx_to_char_idx(cursorPos, code); // Get completions from Jupyter kernel if its Channels is connected let items = []; if (this.channels) { try { const message = completionRequest(code, cursorPos); items = await this.codeCompleteObservable( this.channels, message, model ).toPromise(); } catch (error) { // tslint:disable-next-line console.error(error); } } return Promise.resolve<monaco.languages.CompletionList>({ suggestions: items, incomplete: false, }); } /** * Get list of completion items from Jupyter kernel. * @param channels Channels of Jupyter kernel. * @param message Jupyter message for completion request. * @param model Text model. */ private codeCompleteObservable( channels: Channels, message: JupyterMessage, model: monaco.editor.ITextModel ) { // Process completion response const completion$ = channels.pipe( childOf(message), ofMessageType("complete_reply"), map((entry) => entry.content), first(), map((results) => this.adaptToMonacoCompletions(results, model)) ); // Subscribe and send completion request message return Observable.create((observer: Observer<any>) => { const subscription = completion$.subscribe(observer); channels.next(message); return subscription; }); } /** * Converts Jupyter completion result to list of Monaco completion items. */ private adaptToMonacoCompletions( results: CompletionResults, model: monaco.editor.ITextModel ) { let range: monaco.IRange; let percentCount = 0; let matches = results ? results.matches : []; if (results.metadata && results.metadata._jupyter_types_experimental) { matches = results.metadata._jupyter_types_experimental; } // retrieve the text that is currently typed out which is used to determine completion const startPos = model.getPositionAt(results.cursor_start); const endPos = model.getPositionAt(results.cursor_end); const context = model.getValueInRange( { startLineNumber: startPos.lineNumber, startColumn: startPos.column, endLineNumber: endPos.lineNumber, endColumn: endPos.column }); return matches.map((match: CompletionMatch, index: number) => { if (typeof match === "string") { const text = this.sanitizeText(match, context); const inserted = this.getInsertText(text, context); const filtered = this.getFilterText(text, context); return { kind: this.adaptToMonacoCompletionItemKind(unknownJupyterKind), label: text, insertText: inserted, filterText: filtered, sortText: this.getSortText(index), } as monaco.languages.CompletionItem; } else { // We only need to get the range once as the range is the same for all completion items in the list. if (!range) { const start = model.getPositionAt(match.start); const end = model.getPositionAt(match.end); range = { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column, }; // Get the range representing the text before the completion action was invoked. // If the text starts with magics % indicator, we need to track how many of these indicators exist // so that we ensure the insertion text only inserts the delta between what the user typed versus // what is recommended by the completion. Without this, there will be extra % insertions. // Example: // User types %%p then suggestion list will recommend %%python, if we now commit the item then the // final text in the editor becomes %%p%%python instead of %%python. This is why the tracking code // below is needed. This behavior is only specific to the magics % indicators as Monaco does not // handle % characters in their completion list well. const rangeText = model.getValueInRange(range); if (rangeText.startsWith("%%")) { percentCount = 2; } else if (rangeText.startsWith("%")) { percentCount = 1; } } const text = this.sanitizeText(match.text, context); const filtered = this.getFilterText(text, context); const inserted = this.getInsertText(text, context, percentCount); return { kind: this.adaptToMonacoCompletionItemKind(match.type), label: text, insertText: inserted, filterText: filtered, sortText: this.getSortText(index), } as monaco.languages.CompletionItem; } }); } /** * Converts Jupyter completion item kind to Monaco completion item kind. * @param kind Jupyter completion item kind. */ private adaptToMonacoCompletionItemKind(kind: string) { const result = jupyterToMonacoCompletionItemKind[kind]; return result ? result : jupyterToMonacoCompletionItemKind[unknownJupyterKind]; } /** * Removes problematic prefixes based on the context. * * Instead of showing "some/path" we should only show "path". For paths with white space, the kernel returns * ""some/path with spaces"" which we want to change to ""path with spaces"". * * Additionally, typing "[]." should not suggest ".append" since this results in "[]..append". * * @param text Text of Jupyter completion item */ private sanitizeText(text: string, context: string) { // Assumption: if the current context contains a "/" then we're currently typing a path const isPathCompletion = context.includes("/"); if (isPathCompletion) { // If we have whitespace within a path, the completion for it is a string wrapped in double quotes // We should return only the last part of the path, wrapped in double quotes const completionIsPathWithWhitespace = text.startsWith('"') && text.endsWith('"') && text.length > 2; // sanity check: not empty string if (completionIsPathWithWhitespace && text.substr(1).startsWith(context)) { // sanity check: the context is part of the suggested path const toRemove = context.substr(0, context.lastIndexOf("/") + 1); return `"${text.substr(toRemove.length+1)}`; } // Otherwise, display the most specific item in the path if (text.startsWith(context)) { // sanity check: the context is part of the suggested path const toRemove = context.substr(0, context.lastIndexOf("/") + 1); return text.substr(toRemove.length); } } // Handle "." after paths, since those might contain "." as well. Note that we deal with this somewhat // generically, but also take a somewhat conservative approach by ensuring that the completion starts with the // current context to ensure that we aren't applying this when we shouldn't const isMemberCompletion = context.endsWith("."); if (isMemberCompletion && text.startsWith(context)) { const toRemove = context.substr(0, context.lastIndexOf(".") + 1); return text.substr(toRemove.length); } // Handle taking only the suggestion content after the last dot. There are cases that a kernel when given // "suggestion1.itemA" text and typing "." that it will suggest the full path of "suggestion.itemA.itemB" instead of // just "itemB". The logic below handles these cases. This also handles the case where given "suggestion1.itemA.it" // text and typing "e" will suggest the full path of "suggestion.itemA.itemB" instead of "itemB". // This logic also covers that scenario. const index = text.lastIndexOf("."); if (index > -1 && index < text.length - 1) { return text.substring(index + 1); } return text; } /** * Remove magics all % characters as Monaco doesn't like them for the filtering text. * Without this, completion won't show magics match items. * * Also remove quotes from the filter of a path wrapped in quotes to make sure we have * a smooth auto-complete experience. * * @param text Text of Jupyter completion item. */ private getFilterText(text: string, context: string) { const isPathCompletion = context.includes("/"); if (isPathCompletion) { const completionIsPathWithWhitespace = text.startsWith('"') && text.endsWith('"') && text.length > 2; // sanity check: not empty string if (completionIsPathWithWhitespace && text.substr(1).startsWith(context)) { // sanity check: the context is part of the suggested path return text.substr(1, text.length-1); } } return text.replace(/%/g, ""); } /** * Get insertion text handling what to insert for the magics case depending on what * has already been typed. Also handles an edge case for file paths with "." in the name. * @param text Text of Jupyter completion item. * @param percentCount Number of percent characters to remove */ private getInsertText(text: string, context: string, percentCount: number = 0) { // There is an edge case for folders that have "." in the name. The default range for replacements is determined // by the "current word" but that doesn't allow "." in the string, so if you autocomplete "some." for a string // like "some.folder.name" you end up with "some.some.folder.name". const isPathCompletion = context.includes("/"); const isPathWithPeriodInName = isPathCompletion && text.includes(".") && context.includes("."); if (isPathWithPeriodInName) { // The text in our sanitization step has already been filtered to only include the most specific path but // our context includes the full thing, so we need to determine the substring in the most specific path. // This is then used to figure out what we should actually insert. // example 1: context = "a/path/to/some." and text = "some.folder.name" should produce "folder.name" // example 2: context = "a/path/to/some.fo" and text = "some.folder.name" should still produce "folder.name" const completionContext = context.substr(context.lastIndexOf("/") + 1); if (text.startsWith(completionContext)) { // sanity check: the paths match return text.substr(completionContext.lastIndexOf(".") + 1); } } for (let i = 0; i < percentCount; i++) { text = text.replace("%", ""); } return text; } /** * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicograhically. * 1 -> "za", 26 -> "zz", 27 -> "zza", 28 -> "zzb", 52 -> "zzz", 53 ->"zzza" * @param order Number to be converted to a sorting-string. order >= 0. * @returns A string representing the order. */ private getSortText(order: number): string { order++; const numCharacters = 26; // "z" - "a" + 1; const div = Math.floor(order / numCharacters); let sortText = "z"; for (let i = 0; i < div; i++) { sortText += "z"; } const remainder = order % numCharacters; if (remainder > 0) { sortText += String.fromCharCode(96 + remainder); } return sortText; } } const completionProvider = new CompletionItemProvider(); export { completionProvider };
the_stack
import { MIRConstructableEntityTypeDecl, MIREntityTypeDecl, MIRInvokeBodyDecl, MIRPCode, MIRPrimitiveListEntityTypeDecl, MIRType } from "../../compiler/mir_assembly"; import { MIRInvokeKey, MIRResolvedTypeKey } from "../../compiler/mir_ops"; import { SMTTypeEmitter } from "./smttype_emitter"; import { SMTFunction, SMTFunctionUninterpreted } from "./smt_assembly"; import { BVEmitter, SMTCallGeneral, SMTCallSimple, SMTCond, SMTConst, SMTExists, SMTExp, SMTForAll, SMTIf, SMTLet, SMTLetMulti, SMTType, SMTVar, VerifierOptions } from "./smt_exp"; import * as assert from "assert"; class RequiredListConstructors { //always empty, 1, 2, 3 //always slice //always concat2 havoc: boolean = false; fill: boolean = false; filter: boolean = false; map: Map<string, {code: MIRPCode, fromtype: MIRType, totype: MIRType, isidx: boolean}> = new Map<string, {code: MIRPCode, fromtype: MIRType, totype: MIRType, isidx: boolean}>(); } type SMTConstructorGenCode = { uf: SMTFunctionUninterpreted[], if: SMTFunction[], cons: { cname: string, cargs: { fname: string, ftype: SMTType }[] } }; class RequiredListDestructors { //always get safecheckpred: Map<string, {code: MIRPCode, isidx: boolean}> = new Map<string, {code: MIRPCode, isidx: boolean}>(); safecheckfn: Map<string, {code: MIRPCode, rtype: MIRType, isidx: boolean}> = new Map<string, {code: MIRPCode, rtype: MIRType, isidx: boolean}>(); isequence: Map<string, {code: MIRPCode, isidx: boolean}> = new Map<string, {code: MIRPCode, isidx: boolean}>(); haspredcheck: Map<string, {code: MIRPCode, isidx: boolean}> = new Map<string, {code: MIRPCode, isidx: boolean}>(); findIndexOf: Map<string, {code: MIRPCode, isidx: boolean}> = new Map<string, {code: MIRPCode, isidx: boolean}>(); findLastIndexOf: Map<string, {code: MIRPCode, isidx: boolean}> = new Map<string, {code: MIRPCode, isidx: boolean}>(); sum: boolean = false; strconcat: boolean = false; strjoin: boolean = false; } type SMTDestructorGenCode = { uf: SMTFunctionUninterpreted[], if: SMTFunction[] }; class ListOpsInfo { readonly ltype: MIRType; readonly ctype: MIRType; consops: RequiredListConstructors; dops: RequiredListDestructors; constructor(ltype: MIRType, ctype: MIRType) { this.ltype = ltype; this.ctype = ctype; this.consops = new RequiredListConstructors(); this.dops = new RequiredListDestructors(); } } class ListOpsManager { readonly vopts: VerifierOptions readonly temitter: SMTTypeEmitter; readonly numgen: BVEmitter; readonly safecalls: Set<MIRInvokeKey>; rangenat: boolean = false; rangeint: boolean = false; ops: Map<string, ListOpsInfo> = new Map<string, ListOpsInfo>(); private tmpvarctr = 0; private booltype: SMTType; private nattype: SMTType; generateTempName(): string { return `_@tmpvar_cc@${this.tmpvarctr++}`; } constructor(vopts: VerifierOptions, temitter: SMTTypeEmitter, numgen: BVEmitter, safecalls: Set<MIRInvokeKey>) { this.vopts = vopts; this.temitter = temitter; this.numgen = numgen; this.safecalls = safecalls; this.booltype = this.temitter.getSMTTypeFor(this.temitter.getMIRType("NSCore::Bool")); this.nattype = this.temitter.getSMTTypeFor(this.temitter.getMIRType("NSCore::Nat")); } private ensureOpsFor(encltype: MIRType): ListOpsInfo { if (!this.ops.has(encltype.typeID)) { const stypeinfo = this.temitter.assembly.entityDecls.get(encltype.typeID) as MIRPrimitiveListEntityTypeDecl; const ctype = stypeinfo.terms.get("T") as MIRType; this.ops.set(encltype.typeID, new ListOpsInfo(encltype, ctype)); } return this.ops.get(encltype.typeID) as ListOpsInfo; } registerHavoc(ltype: MIRType): string { const ops = this.ensureOpsFor(ltype); ops.consops.havoc = true; return this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "havoc"); } processHavoc(ltype: MIRType, path: SMTVar): SMTExp { const ops = this.ensureOpsFor(ltype); ops.consops.havoc = true; return new SMTCallSimple(this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "havoc"), [path]); } processLiteralK_Pos(ltype: MIRType, values: SMTExp[]): SMTExp { const opname = `list_${values.length}`; return new SMTCallSimple(this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), opname), values); } processGet(ltype: MIRType, l: SMTExp, n: SMTExp): SMTExp { this.ensureOpsFor(ltype); const op = this.generateDesCallName(this.temitter.getSMTTypeFor(ltype), "get"); //get always registered return new SMTCallSimple(op, [l, n]); } processSafePredCheck(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "safeCheckPred" + (isidx ? "_idx" : ""), code); ops.dops.safecheckpred.set(code, {code: pcode, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processSafeFnCheck(ltype: MIRType, rtype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp,capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "safeCheckFn" + (isidx ? "_idx" : ""), code); ops.dops.safecheckfn.set(code, {code: pcode, rtype: rtype, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processISequence(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "isequence" + (isidx ? "_idx" : ""), code); ops.dops.isequence.set(code, {code: pcode, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processHasPredCheck(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "hasPredCheck" + (isidx ? "_idx" : ""), code); ops.dops.haspredcheck.set(code, {code: pcode, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processFindIndexOf(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "findIndexOf" + (isidx ? "_idx" : ""), code); ops.dops.findIndexOf.set(code, {code: pcode, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processFindLastIndexOf(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallNameUsing(this.temitter.getSMTTypeFor(ltype), "findLastIndexOf" + (isidx ? "_idx" : ""), code); ops.dops.findLastIndexOf.set(code, {code: pcode, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processConcat2(ltype: MIRType, l1: SMTExp, l2: SMTExp, count: SMTExp): SMTExp { this.ensureOpsFor(ltype); const op = this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "concat2"); //concat always registered return new SMTCallSimple(op, [l1, l2, count]); } processSlice(ltype: MIRType, l1: SMTExp, start: SMTExp, end: SMTExp, count: SMTExp): SMTExp { this.ensureOpsFor(ltype); const op = this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "slice"); //slice always registered return new SMTCallSimple(op, [l1, start, end, count]); } processRangeOfIntOperation(ltype: MIRType, start: SMTExp, end: SMTExp, count: SMTExp): SMTExp { this.ensureOpsFor(ltype); this.rangeint = true; return new SMTCallSimple(this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "rangeOfInt"), [start, end, count]); } processRangeOfNatOperation(ltype: MIRType, start: SMTExp, end: SMTExp, count: SMTExp): SMTExp { this.ensureOpsFor(ltype); this.rangenat = true; return new SMTCallSimple(this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "rangeOfNat"), [start, end, count]); } processFillOperation(ltype: MIRType, count: SMTExp, value: SMTExp): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "fill"); ops.consops.fill = true; return new SMTCallSimple(op, [count, value]); } processMap(ltype: MIRType, intotype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTExp, count: SMTExp, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(intotype); const op = this.generateConsCallNameUsing(this.temitter.getSMTTypeFor(intotype), "map" + (isidx ? "_idx" : ""), code); ops.consops.map.set(code, {code: pcode, fromtype: ltype, totype: intotype, isidx: isidx}); return new SMTCallGeneral(op, [l, count, ...capturedargs]); } processFilter(ltype: MIRType, isidx: boolean, code: string, pcode: MIRPCode, l: SMTVar, isq: SMTVar, count: SMTVar, capturedargs: SMTVar[]): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateConsCallName(this.temitter.getSMTTypeFor(ltype), "filter" + (isidx ? "_idx" : "")); ops.consops.filter = true; return new SMTCallGeneral(op, [l, isq, count, ...capturedargs]); } processSum(ltype: MIRType, l: SMTExp): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallName(this.temitter.getSMTTypeFor(ltype), "sum"); ops.dops.sum = true; return new SMTCallGeneral(op, [l]); } processStrConcat(ltype: MIRType, l: SMTExp): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallName(this.temitter.getSMTTypeFor(ltype), "strconcat"); ops.dops.strconcat = true; return new SMTCallGeneral(op, [l]); } processStrJoin(ltype: MIRType, l: SMTExp, sep: SMTExp): SMTExp { const ops = this.ensureOpsFor(ltype); const op = this.generateDesCallName(this.temitter.getSMTTypeFor(ltype), "strjoin"); ops.dops.strjoin = true; return new SMTCallGeneral(op, [l, sep]); } generateConsCallName(ltype: SMTType, opname: string): string { return `_@@consop_${ltype.name}_${opname}`; } generateConsCallNameUsing(ltype: SMTType, opname: string, code: string): string { return `_@@consop_${ltype.name}_${opname}_using_${this.temitter.lookupFunctionName(code)}`; } generateDesCallName(ltype: SMTType, opname: string): string { return `_@@desop_${ltype.name}_${opname}`; } generateDesCallNameUsing(ltype: SMTType, opname: string, code: string): string { return `_@@desop_${ltype.name}_${opname}_using_${this.temitter.lookupFunctionName(code)}`; } generateULITypeFor(ltype: SMTType): SMTType { return new SMTType(ltype.name + "$uli", "[INTERNAL TYPE]", ltype.typeID + "$uli"); } generateULIFieldFor(ltype: SMTType, consname: string, fname: string): string { return this.generateConsCallName_Direct(ltype, consname) + "_" + fname; } generateULIFieldUsingFor(ltype: SMTType, consname: string, code: string, fname: string): string { return this.generateConsCallNameUsing_Direct(ltype, consname, code) + "_" + fname; } generateConsCallName_Direct(ltype: SMTType, opname: string): string { return `_@@cons_${ltype.name}_${opname}`; } generateConsCallNameUsing_Direct(ltype: SMTType, opname: string, code: string): string { return `_@@cons_${ltype.name}_${opname}_using_${this.temitter.lookupFunctionName(code)}`; } generateListSizeCall(exp: SMTExp, etype: SMTType): SMTExp { return new SMTCallSimple(`${etype.name}@size`, [exp]); } generateListContentsCall(exp: SMTExp, etype: SMTType): SMTExp { return new SMTCallSimple(`${etype.name}@uli`, [exp]); } generateGetULIFieldFor(ltype: SMTType, consname: string, fname: string, arg: SMTExp): SMTExp { return new SMTCallSimple(this.generateULIFieldFor(ltype, consname, fname), [arg]); } generateGetULIFieldUsingFor(ltype: SMTType, consname: string, code: string, fname: string, arg: SMTExp): SMTExp { return new SMTCallSimple(this.generateULIFieldUsingFor(ltype, consname, code, fname), [arg]); } emitConstructorEmpty(mtype: MIRType, ltype: SMTType): SMTConstructorGenCode { const ffunc = new SMTCallSimple(this.temitter.getSMTConstructorName(mtype).cons, [ new SMTConst("BNat@zero"), new SMTCallSimple(this.generateConsCallName_Direct(ltype, "empty"), []) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, "empty"), cargs: [] }, if: [new SMTFunction(this.generateConsCallName(ltype, "empty"), [], undefined, 0, ltype, ffunc)], uf: [] } } //////// //Slice emitConstructorSlice(mtype: MIRType, ltype: SMTType): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const ffunc = new SMTCallSimple(lcons, [ new SMTVar("count"), new SMTCallSimple(this.generateConsCallName_Direct(ltype, "slice"), [new SMTVar("l"), new SMTVar("start"), new SMTVar("end")]) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, "slice"), cargs: [{ fname: this.generateULIFieldFor(ltype, "slice", "l"), ftype: ltype }, { fname: this.generateULIFieldFor(ltype, "slice", "start"), ftype: this.nattype }, { fname: this.generateULIFieldFor(ltype, "slice", "end"), ftype: this.nattype }] }, if: [new SMTFunction(this.generateConsCallName(ltype, "slice"), [{ vname: "l", vtype: ltype }, { vname: "start", vtype: this.nattype }, { vname: "end", vtype: this.nattype }, { vname: "count", vtype: this.nattype }], undefined, 0, ltype, ffunc)], uf: [] }; } //////// //Concat emitConstructorConcat2(mtype: MIRType, ltype: SMTType): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const ffunc = new SMTCallSimple(lcons, [ new SMTVar("count"), new SMTCallSimple(this.generateConsCallName_Direct(ltype, "concat2"), [new SMTVar("l1"), new SMTVar("l2")]) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, "concat2"), cargs: [{ fname: this.generateULIFieldFor(ltype, "concat2", "left"), ftype: ltype }, { fname: this.generateULIFieldFor(ltype, "concat2", "right"), ftype: ltype }] }, if: [new SMTFunction(this.generateConsCallName(ltype, "concat2"), [{ vname: "l1", vtype: ltype }, { vname: "l2", vtype: ltype }, { vname: "count", vtype: this.nattype }], undefined, 0, ltype, ffunc)], uf: [] }; } //////// //Havoc emitConstructorHavoc(mtype: MIRType, ltype: SMTType, ctype: MIRType): SMTConstructorGenCode { assert(this.vopts.EnableCollection_SmallHavoc || this.vopts.EnableCollection_LargeHavoc); const lcons = this.temitter.getSMTConstructorName(mtype).cons; const ptype = this.temitter.getSMTTypeFor(this.temitter.getMIRType("NSCore::HavocSequence")); const size = "_@size"; const sizev = new SMTVar(size); const emptyopt = { test: SMTCallSimple.makeEq(sizev, new SMTConst("BNat@zero")), result: this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTConst(`${this.temitter.lookupTypeName(mtype.typeID)}@empty_const`)) }; const smallmodeopts = [ { test: SMTCallSimple.makeEq(sizev, this.numgen.emitSimpleNat(1)), result: new SMTLetMulti([ { vname: "_@val0", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(0)) } ], new SMTIf(this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val0")), this.temitter.generateErrorResultAssert(mtype), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(this.generateConsCallName(ltype, "list_1"), [ this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val0")) ]) ) ) ) }, { test: SMTCallSimple.makeEq(sizev, this.numgen.emitSimpleNat(2)), result: new SMTLetMulti([ { vname: "_@val0", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(0)) }, { vname: "_@val1", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(1)) } ], new SMTIf(SMTCallSimple.makeOrOf( this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val0")), this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val1")) ), this.temitter.generateErrorResultAssert(mtype), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(this.generateConsCallName(ltype, "list_2"), [ this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val0")), this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val1")) ])) ) ) }, { test: SMTCallSimple.makeEq(sizev, this.numgen.emitSimpleNat(3)), result: new SMTLetMulti([ { vname: "_@val0", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(0)) }, { vname: "_@val1", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(1)) }, { vname: "_@val2", value: this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), this.numgen.emitSimpleNat(2)) } ], new SMTIf(new SMTCallSimple("or", [ this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val0")), this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val1")), this.temitter.generateResultIsErrorTest(ctype, new SMTVar("_@val2")) ]), this.temitter.generateErrorResultAssert(mtype), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(this.generateConsCallName(ltype, "list_3"), [ this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val0")), this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val1")), this.temitter.generateResultGetSuccess(ctype, new SMTVar("_@val2")) ])) ) ) } ]; let largemodeopts = new SMTIf(new SMTForAll([{ vname: "_@n", vtype: this.nattype }], new SMTCallSimple("=>", [ new SMTCallSimple("bvult", [new SMTVar("_@n"), sizev]), this.temitter.generateResultIsSuccessTest(ctype, this.temitter.generateHavocConstructorCall(ctype, new SMTVar("path"), new SMTVar("_@n"))) ]) ), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(lcons, [sizev, new SMTCallSimple(this.generateConsCallName_Direct(ltype, "havoc"), [new SMTVar("path")])])), this.temitter.generateErrorResultAssert(mtype) ); let ffunc: SMTExp = new SMTConst("[UNINIT]"); if(this.vopts.EnableCollection_SmallHavoc && !this.vopts.EnableCollection_LargeHavoc) { ffunc = new SMTLet(size, new SMTCallSimple("ListSize@UFCons_API", [new SMTVar("path")]), new SMTCond([emptyopt, ...smallmodeopts.slice(0, smallmodeopts.length - 1)], smallmodeopts[smallmodeopts.length - 1].result) ); } else if (!this.vopts.EnableCollection_SmallHavoc && this.vopts.EnableCollection_LargeHavoc) { ffunc = new SMTLet(size, new SMTCallSimple("ListSize@UFCons_API", [new SMTVar("path")]), new SMTIf(emptyopt.test, emptyopt.result, largemodeopts) ); } else { ffunc = new SMTLet(size, new SMTCallSimple("ListSize@UFCons_API", [new SMTVar("path")]), new SMTCond([emptyopt, ...smallmodeopts], largemodeopts) ); } return { cons: { cname: this.generateConsCallName_Direct(ltype, "havoc"), cargs: [{ fname: this.generateULIFieldFor(ltype, "havoc", "path"), ftype: ptype }] }, if: [new SMTFunction(this.generateConsCallName(ltype, "havoc"), [{ vname: "path", vtype: ptype }], undefined, 0, this.temitter.generateResultType(mtype), ffunc)], uf: [] }; } //////// //Fill emitConstructorFill(mtype: MIRType, ltype: SMTType, ctype: MIRType): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const ffunc = new SMTCallSimple(lcons, [ new SMTVar("count"), new SMTCallSimple(this.generateConsCallName_Direct(ltype, "fill"), [new SMTVar("value")]) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, "fill"), cargs: [{ fname: this.generateULIFieldFor(ltype, "fill", "value"), ftype: this.temitter.getSMTTypeFor(ctype) }] }, if: [new SMTFunction(this.generateConsCallName(ltype, "fill"), [{ vname: "value", vtype: this.temitter.getSMTTypeFor(ctype) }, { vname: "count", vtype: this.nattype }], undefined, 0, ltype, ffunc)], uf: [] }; } //////// //RangeNat/Int emitConstructorRange(mtype: MIRType, ltype: SMTType, ctype: MIRType): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const opname = ctype.typeID === "NSCore::Nat" ? "rangeOfNat" : "rangeOfInt"; const rtype = this.temitter.getSMTTypeFor(ctype); const ffunc = new SMTCallSimple(lcons, [ new SMTCallSimple("bvsub", [new SMTVar("end"), new SMTVar("start")]), new SMTCallSimple(this.generateConsCallName_Direct(ltype, opname), [new SMTVar("start"), new SMTVar("end")]) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, opname), cargs: [{ fname: this.generateULIFieldFor(ltype, opname, "start"), ftype: rtype }, { fname: this.generateULIFieldFor(ltype, opname, "end"), ftype: rtype }] }, if: [new SMTFunction(this.generateConsCallName(ltype, opname), [{ vname: "start", vtype: rtype }, { vname: "end", vtype: rtype }, { vname: "count", vtype: this.nattype }], undefined, 0, ltype, ffunc)], uf: [] }; } //////// //LiteralK emitConstructorLiteralK(mtype: MIRType, ltype: SMTType, ctype: MIRType, k: number): SMTConstructorGenCode { const smtctype = this.temitter.getSMTTypeFor(ctype); const opname = `list_${k}`; let kfields: {fname: string, ftype: SMTType}[] = []; let kfargs: {vname: string, vtype: SMTType}[] = []; for(let i = 0; i < k; ++i) { kfields.push({fname: this.generateULIFieldFor(ltype, opname, `_${i}_`), ftype: smtctype}); kfargs.push({vname: `_${i}_`, vtype: smtctype}); } //default construct const ffunc = new SMTCallSimple(this.temitter.getSMTConstructorName(mtype).cons, [ this.numgen.emitSimpleNat(k), new SMTCallSimple(this.generateConsCallName_Direct(ltype, opname), kfargs.map((arg) => new SMTVar(arg.vname))) ]); return { cons: { cname: this.generateConsCallName_Direct(ltype, opname), cargs: kfields }, if: [new SMTFunction(this.generateConsCallName(ltype, opname), kfargs, undefined, 0, ltype, ffunc)], uf: [] }; } //////// //Filter emitConstructorFilter(ltype: SMTType, mtype: MIRType): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const ffunc: SMTExp = this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(lcons, [ new SMTCallSimple("ISequence@size", [new SMTVar("isq")]), new SMTCallSimple(this.generateConsCallName_Direct(ltype, "filter"), [new SMTVar("l"), new SMTVar("isq")]) ]) ); const iseqtype = this.temitter.getSMTTypeFor(this.temitter.getMIRType("NSCore::ISequence")); return { cons: { cname: this.generateConsCallName_Direct(ltype, "filter"), cargs: [{ fname: this.generateULIFieldFor(ltype, "filter", "l"), ftype: ltype }, { fname: this.generateULIFieldFor(ltype, "filter", "isq"), ftype: iseqtype }] }, if: [new SMTFunction(this.generateConsCallName(ltype, "filter"), [{ vname: "l", vtype: ltype }, { vname: "isq", vtype: iseqtype }, { vname: "osize", vtype: this.nattype }], undefined, 0, this.temitter.generateResultType(mtype), ffunc)], uf: [] }; } //////// //Map emitConstructorMap(ltype: SMTType, mtype: MIRType, fromtype: MIRType, isidx: boolean, code: string, pcode: MIRPCode): SMTConstructorGenCode { const lcons = this.temitter.getSMTConstructorName(mtype).cons; const constype = this.temitter.getSMTTypeFor(mtype); const mapname = "map" + (isidx ? "_idx" : ""); const capturedfields = this.generateCapturedFieldInfoFor(ltype, mapname, isidx ? 2 : 1, code, pcode); const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); const ffunc = this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTCallSimple(lcons, [ new SMTVar("count"), new SMTCallSimple(this.generateConsCallNameUsing_Direct(constype, mapname, code), [new SMTVar("l"), ...capturedargs]) ]) ); return { cons: { cname: this.generateConsCallNameUsing_Direct(constype, mapname, code), cargs: [{ fname: this.generateULIFieldUsingFor(ltype, mapname, code, "l"), ftype: this.temitter.getSMTTypeFor(fromtype) }, ...capturedfields] }, if: [new SMTFunction(this.generateConsCallNameUsing(constype, mapname, code), [{ vname: "l", vtype: this.temitter.getSMTTypeFor(fromtype) }, { vname: "count", vtype: this.nattype }, ...capturedparams], undefined, 0, this.temitter.generateResultType(mtype), ffunc)], uf: [] }; } //////// //Get emitDestructorGet_Slice(getop: string, ltype: SMTType, ll: SMTVar, n: SMTVar): SMTExp { return new SMTCallSimple(getop, [ this.generateGetULIFieldFor(ltype, "slice", "l", ll), new SMTCallSimple("bvadd", [ n, this.generateGetULIFieldFor(ltype, "slice", "start", ll) ]) ]); } emitDestructorGet_Concat2(getop: string, ltype: SMTType, ll: SMTVar, n: SMTVar): SMTExp { const l1 = "_@l1"; const l1v = new SMTVar(l1); const l1s = "_@l1size"; const l1sv = new SMTVar(l1s); return new SMTLet(l1, this.generateGetULIFieldFor(ltype, "concat2", "left", ll), new SMTLet(l1s, this.generateListSizeCall(l1v, ltype), new SMTIf(new SMTCallSimple("bvult", [n, l1sv]), new SMTCallSimple(getop, [l1v, n]), new SMTCallSimple(getop, [this.generateGetULIFieldFor(ltype, "concat2", "right", ll), new SMTCallSimple("bvsub", [n, l1sv])]) ) ) ); } emitDestructorGet_K(ltype: SMTType, ll: SMTVar, n: SMTVar, k: number, ): SMTExp { if (k === 1) { return this.generateGetULIFieldFor(ltype, "list_1", "_0_", ll); } else { let kops: { test: SMTExp, result: SMTExp }[] = []; for (let i = 0; i < k - 1; ++i) { kops.push({ test: SMTCallSimple.makeEq(n, this.numgen.emitSimpleNat(i)), result: this.generateGetULIFieldFor(ltype, `list_${k}`, `_${i}_`, ll) }); } const klast = this.generateGetULIFieldFor(ltype, `list_${k}`, `_${k - 1}_`, ll) return new SMTCond( kops, klast ); } } emitDestructorGet_Filter(getop: string, ltype: SMTType, ll: SMTVar, n: SMTVar): SMTExp { return new SMTLet("_@olist", this.generateGetULIFieldFor(ltype, "filter", "l", ll), new SMTCallSimple(getop, [new SMTVar("_@olist"), new SMTCallSimple("ISequence@get", [this.generateGetULIFieldFor(ltype, "filter", "isq", ll), n])]) ); } emitDestructorGet_Map(ctype: MIRType, srcltype: SMTType, fromtype: MIRType, ll: SMTVar, n: SMTVar, isidx: boolean, code: string, pcode: MIRPCode): SMTExp { const getop = this.generateDesCallName(this.temitter.getSMTTypeFor(fromtype), "get"); const mapname = "map" + (isidx ? "_idx" : ""); const capturedfieldlets = this.generateCapturedFieldLetsInfoFor(srcltype, mapname, isidx ? 2 : 1, code, pcode, ll); const largs = isidx ? [new SMTCallSimple(getop, [new SMTVar("_@olist"), n]), n] : [new SMTCallSimple(getop, [new SMTVar("_@olist"), n])]; return new SMTLet("_@olist", this.generateGetULIFieldUsingFor(srcltype, mapname, code, "l", ll), this.processCapturedFieldLets(capturedfieldlets, this.generateLambdaCallKnownSafe(code, ctype, largs, capturedfieldlets.map((cfl) => new SMTVar(cfl.vname))) ) ); } emitDestructorGet(ltype: SMTType, ctype: MIRType, consopts: RequiredListConstructors | undefined): SMTDestructorGenCode { const getop = this.generateDesCallName(ltype, "get"); const llv = new SMTVar("_@list_contents"); let tsops: { test: SMTExp, result: SMTExp }[] = []; for(let i = 1; i <= 3; ++i) { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, `list_${i}`), llv), result: this.emitDestructorGet_K(ltype, llv, new SMTVar("n"), i) }); } //always slice tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "slice"), llv), result: this.emitDestructorGet_Slice(getop, ltype, llv, new SMTVar("n")) }); //always concat2 tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "concat2"), llv), result: this.emitDestructorGet_Concat2(getop, ltype, llv, new SMTVar("n")) }); if (consopts !== undefined) { if (consopts.havoc) { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "havoc"), llv), result: this.temitter.generateResultGetSuccess(ctype, this.temitter.generateHavocConstructorCall(ctype, this.generateGetULIFieldFor(ltype, "havoc", "path", llv), new SMTVar("n"))) }); } if (consopts.fill) { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "fill"), llv), result: this.generateGetULIFieldFor(ltype, "fill", "v", llv) }); } if (this.rangenat && ctype.typeID === "NSCore::Nat") { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "rangeOfNat"), llv), result: new SMTCallSimple("bvadd", [this.generateGetULIFieldFor(ltype, "rangeOfNat", "start", llv), new SMTVar("n")]) }); } if (this.rangeint && ctype.typeID === "NSCore::Int") { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "rangeOfInt"), llv), result: new SMTCallSimple("bvadd", [this.generateGetULIFieldFor(ltype, "rangeOfInt", "start", llv), new SMTVar("n")]) }); } if(consopts.filter) { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallName_Direct(ltype, "filter"), llv), result: this.emitDestructorGet_Filter(getop, ltype, llv, new SMTVar("n")) }); } consopts.map.forEach((omi, code) => { tsops.push({ test: SMTCallSimple.makeIsTypeOp(this.generateConsCallNameUsing_Direct(ltype, omi.isidx ? "map_idx" : "map", code), llv), result: this.emitDestructorGet_Map(ctype, ltype, omi.fromtype, llv, new SMTVar("n"), omi.isidx, code, omi.code) }); }); } const ffunc = new SMTLetMulti([{ vname: "_@list_contents", value: this.generateListContentsCall(new SMTVar("l"), ltype) }], new SMTCond(tsops.slice(0, tsops.length - 1), tsops[tsops.length - 1].result) ); return { if: [new SMTFunction(this.generateDesCallName(ltype, "get"), [{ vname: "l", vtype: ltype }, { vname: "n", vtype: this.nattype}], undefined, 0, this.temitter.getSMTTypeFor(ctype), ffunc)], uf: [] }; } //////// //SafeCheck emitSafeCheckPred(ltype: SMTType, mtype: MIRType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const restype = this.temitter.getMIRType("NSCore::Bool"); const safename = "safeCheckPred" + (isidx ? "_idx" : ""); const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@n")]); const largs = isidx ? [getcall, new SMTVar("_@n")] : [getcall]; const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); if (this.safecalls.has(code)) { return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, safename, code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(mtype), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTVar("l")))], uf: [] }; } else { const tecase = new SMTExists([{ vname: "_@n", vtype: this.nattype }], SMTCallSimple.makeAndOf( new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTVar("count")]), SMTCallSimple.makeEq( this.generateLambdaCallGeneral(code, restype, largs, capturedargs), this.temitter.generateResultTypeConstructorError(restype, new SMTConst("ErrorID_Target")) ) ) ); const gecase = new SMTExists([{ vname: "_@n", vtype: this.nattype }], SMTCallSimple.makeAndOf( new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTVar("count")]), SMTCallSimple.makeEq( this.generateLambdaCallGeneral(code, restype, largs, capturedargs), this.temitter.generateErrorResultAssert(restype) ) ) ); const ffunc = new SMTCond([ { test: tecase, result: this.temitter.generateResultTypeConstructorError(mtype, new SMTConst("ErrorID_Target")) }, { test: gecase, result: this.temitter.generateErrorResultAssert(mtype) } ], this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTVar("l")) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, safename, code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(mtype), ffunc)], uf: [] }; } } emitSafeCheckFn(ltype: SMTType, mtype: MIRType, restype: MIRType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const safename = "safeCheckFn" + (isidx ? "_idx" : ""); const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@n")]); const largs = isidx ? [getcall, new SMTVar("_@n")] : [getcall]; const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); if (this.safecalls.has(code)) { return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, safename, code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(mtype), this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTVar("l")))], uf: [] }; } else { const tecase = new SMTExists([{ vname: "_@n", vtype: this.nattype }], new SMTCallSimple("and", [ new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTVar("count")]), new SMTCallSimple("=", [ this.generateLambdaCallGeneral(code, restype, largs, capturedargs), this.temitter.generateResultTypeConstructorError(restype, new SMTConst("ErrorID_Target")) ]) ]) ); const gecase = new SMTExists([{ vname: "_@n", vtype: this.nattype }], new SMTCallSimple("and", [ new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTVar("count")]), new SMTCallSimple("=", [ this.generateLambdaCallGeneral(code, restype, largs, capturedargs), this.temitter.generateErrorResultAssert(restype) ]) ]) ); const ffunc = new SMTCond([ { test: tecase, result: this.temitter.generateResultTypeConstructorError(mtype, new SMTConst("ErrorID_Target")) }, { test: gecase, result: this.temitter.generateErrorResultAssert(mtype) } ], this.temitter.generateResultTypeConstructorSuccess(mtype, new SMTVar("l")) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, safename, code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(mtype), ffunc)], uf: [] }; } } //////// //ISequence emitDestructorISequence(ltype: SMTType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const iseqtype = this.temitter.getMIRType("NSCore::ISequence"); const smtiseqtype = this.temitter.getSMTTypeFor(iseqtype); const [capturedargs, capturedparams, ufpickargs] = this.generateCapturedInfoFor(pcode, isidx ? 3 : 2); const cff = new SMTFunctionUninterpreted(this.generateConsCallNameUsing(smtiseqtype, "ISequence@@cons", code), [ltype, this.nattype, ...ufpickargs], smtiseqtype); const cvar = "_@cseq"; const getop = this.generateDesCallName(ltype, "get"); //size(res) <= size(arg0) const assertsize = new SMTCallSimple("bvule", [new SMTCallSimple("ISequence@size", [new SMTVar(cvar)]), new SMTVar("count")]); //\forall n \in [0, size(res)) get(res) < size(arg0) const assertrange = new SMTCallSimple("ISequence@assertValuesRange", [new SMTVar(cvar), new SMTVar("count")]); //sorted constraint const assertsorted = new SMTCallSimple("ISequence@assertSorted", [new SMTVar(cvar)]); //\forall j (j \in [lower, upper) /\ p(get(arg0, j))) => (\exists n \in [0, size(res)) /\ get(res, n) = j) const getarglj = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@j")]); const largslj = isidx ? [getarglj, new SMTVar("_@j")] : [getarglj]; const fromassert = new SMTForAll([{ vname: "_@j", vtype: this.nattype }], new SMTCallSimple("=>", [ SMTCallSimple.makeAndOf( new SMTCallSimple("bvult", [new SMTVar("_@j"), new SMTVar("count")]), this.generateLambdaCallKnownSafe(code, this.temitter.getMIRType("NSCore::Bool"), largslj, capturedargs) ), new SMTExists([{ vname: "_@n", vtype: this.nattype }], SMTCallSimple.makeAndOf( new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTCallSimple("ISequence@size", [new SMTVar(cvar)])]), SMTCallSimple.makeEq( new SMTCallSimple("ISequence@get", [new SMTVar(cvar), new SMTVar("_@n")]), new SMTVar("_@j") ) ) ) ]) ); //\forall n (n \in [0, size(res)), get(res, n) = j) => p(get(arg0, j))) --- j \in [lower, upper) is checked by the ISequence@assertValuesRange action const getarglacc = new SMTCallSimple(getop, [new SMTVar("l"), new SMTCallSimple("ISequence@get", [new SMTVar(cvar), new SMTVar("_@n")])]); const largslacc = isidx ? [getarglacc, new SMTCallSimple("ISequence@get", [new SMTVar(cvar), new SMTVar("_@n")])] : [getarglacc]; const toassert = new SMTForAll([{ vname: "_@n", vtype: this.nattype }], new SMTCallSimple("=>", [ new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTCallSimple("ISequence@size", [new SMTVar(cvar)])]), this.generateLambdaCallKnownSafe(code, this.temitter.getMIRType("NSCore::Bool"), largslacc, capturedargs) ]) ); const icons = new SMTCallSimple(this.generateConsCallNameUsing(smtiseqtype, "ISequence@@cons", code), [new SMTVar("l"), new SMTVar("count"), ...capturedargs]); const fbody = new SMTLet(cvar, icons, new SMTIf( SMTCallSimple.makeAndOf(assertsize, assertrange, assertsorted, fromassert, toassert), new SMTCallSimple("$Result_ISequence@success", [new SMTVar(cvar)]), new SMTCallSimple("$Result_ISequence@error", [new SMTConst("ErrorID_AssumeCheck")]) ) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, "isequence" + (isidx ? "_idx" : ""), code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype }, ...capturedparams], undefined, 0, this.temitter.generateResultType(iseqtype), fbody)], uf: [cff] }; } //////// //HasPredCheck emitDestructorHasPredCheck(ltype: SMTType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@n")]); const largs = isidx ? [getcall, new SMTVar("_@n")] : [getcall]; const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); const ffunc = this.temitter.generateResultTypeConstructorSuccess(this.temitter.getMIRType("NSCore::Bool"), new SMTExists([{ vname: "_@n", vtype: this.nattype }], SMTCallSimple.makeAndOf( new SMTCallSimple("bvult", [new SMTVar("_@n"), new SMTVar("count")]), this.generateLambdaCallKnownSafe(code, this.temitter.getMIRType("NSCore::Bool"), largs, capturedargs) ) ) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, "hasPredCheck" + (isidx ? "_idx" : ""), code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(this.temitter.getMIRType("NSCore::Bool")), ffunc)], uf: [] }; } //////// //FindIndexOf emitDestructorFindIndexOf(ltype: SMTType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const [nn, suf] = this.emitDestructorFindIndexOf_Shared(ltype, isidx, code, pcode, new SMTVar("l"), new SMTVar("count"), new SMTConst("BNat@zero")); const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@j")]); const largs = isidx ? [getcall, new SMTVar("_@j")] : [getcall]; const mirbool = this.temitter.getMIRType("NSCore::Bool"); const mirnat = this.temitter.getMIRType("NSCore::Nat"); const ffunc = new SMTLet("_@n", nn, new SMTIf(this.temitter.generateResultIsErrorTest(mirnat, new SMTVar("_@n")), new SMTVar("_@n"), new SMTIf( new SMTForAll([{ vname: "_@j", vtype: this.nattype }], new SMTCallSimple("=>", [ new SMTCallSimple("bvult", [new SMTVar("_@j"), this.temitter.generateResultGetSuccess(mirnat, new SMTVar("_@n"))]), SMTCallSimple.makeNot(this.generateLambdaCallKnownSafe(code, mirbool, largs, capturedargs)) ]) ), this.temitter.generateResultTypeConstructorSuccess(mirnat, new SMTCallSimple("bvadd", [new SMTVar("bidx"), this.temitter.generateResultGetSuccess(mirnat,new SMTVar("_@n"))])), this.temitter.generateErrorResultAssert(mirnat) ) ) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, "findIndexOf" + (isidx ? "_idx" : ""), code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, { vname: "bidx", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(this.temitter.getMIRType("NSCore::Nat")), ffunc)], uf: [suf] }; } //////// //FindLastIndexOf emitDestructorFindIndexOfLast(ltype: SMTType, isidx: boolean, code: string, pcode: MIRPCode): SMTDestructorGenCode { const [nn, suf] = this.emitDestructorFindIndexOf_Shared(ltype, isidx, code, pcode, new SMTVar("l"), new SMTVar("count"), new SMTConst("BNat@max")); const [capturedargs, capturedparams] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [new SMTVar("l"), new SMTVar("_@j")]); const largs = isidx ? [getcall, new SMTVar("_@j")] : [getcall]; const mirbool = this.temitter.getMIRType("NSCore::Bool"); const mirnat = this.temitter.getMIRType("NSCore::Nat"); const ffunc = new SMTLet("_@n", nn, new SMTIf(this.temitter.generateResultIsErrorTest(mirnat, new SMTVar("_@n")), new SMTVar("_@n"), new SMTIf( new SMTForAll([{ vname: "_@j", vtype: this.nattype }], new SMTCallSimple("=>", [ new SMTCallSimple("bvult", [this.temitter.generateResultGetSuccess(mirnat, new SMTVar("_@n")), new SMTVar("_@j")]), SMTCallSimple.makeNot(this.generateLambdaCallKnownSafe(code, mirbool, largs, capturedargs)) ]) ), this.temitter.generateResultTypeConstructorSuccess(mirnat, new SMTCallSimple("bvadd", [new SMTVar("bidx"), this.temitter.generateResultGetSuccess(mirnat,new SMTVar("_@n"))])), this.temitter.generateErrorResultAssert(mirnat) ) ) ); return { if: [new SMTFunction(this.generateDesCallNameUsing(ltype, "findIndexOfLast" + (isidx ? "_idx" : ""), code), [{ vname: "l", vtype: ltype }, { vname: "count", vtype: this.nattype}, { vname: "bidx", vtype: this.nattype}, ...capturedparams], undefined, 0, this.temitter.generateResultType(this.temitter.getMIRType("NSCore::Nat")), ffunc)], uf: [suf] }; } //////// //Sum emitDestructorSum(ltype: SMTType, ctype: MIRType): SMTDestructorGenCode { const restype = this.temitter.generateResultType(ctype); const cdecl = this.temitter.assembly.entityDecls.get(ctype.typeID) as MIREntityTypeDecl; const primtype = cdecl instanceof MIRConstructableEntityTypeDecl ? this.temitter.getMIRType(cdecl.fromtype as MIRResolvedTypeKey) : ctype; let ufconsname: string = "[UN_INITIALIZED]"; let ovfname: string | undefined = undefined; if (primtype.typeID === "NSCore::Int") { ufconsname = "@UFSumConsInt"; ovfname = "@UFSumConsIntOVF"; } else if (primtype.typeID === "NSCore::Nat") { ufconsname = "@UFSumConsNat"; ovfname = "@UFSumConsNatOVF"; } else if (primtype.typeID === "NSCore::BigInt") { ufconsname = "@UFSumConsBigInt"; } else if (primtype.typeID === "NSCore::BigNat") { ufconsname = "@UFSumConsBigNat"; } else if (primtype.typeID === "NSCore::Rational") { ufconsname = "@UFSumConsRational"; } else if (primtype.typeID === "NSCore::Float") { ufconsname = "@UFSumConsFloat"; } else { ufconsname = "@UFSumConsDecimal"; } // //TODO: what about typed numbers -- also min/max // assert(!(cdecl instanceof MIRConstructableEntityTypeDecl) || cdecl.usingcons === undefined, "Yikes this has invariants so we need to havoc"); let ufops = [new SMTFunctionUninterpreted(this.generateDesCallName(ltype, ufconsname), [ltype], this.temitter.getSMTTypeFor(ctype))]; if(ovfname !== undefined) { ufops.push(new SMTFunctionUninterpreted(this.generateDesCallName(ltype, ovfname), [ltype], this.booltype)) } let ffunc: SMTExp = new SMTConst("[UNINIT]"); if(cdecl instanceof MIRConstructableEntityTypeDecl) { if(primtype.typeID !== "NSCore::BigNat") { if(cdecl.usingcons === undefined) { ffunc = this.temitter.generateResultTypeConstructorSuccess(ctype, new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")])); } else { ffunc = new SMTCallGeneral(cdecl.usingcons, [new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")])]); } } else { if(cdecl.usingcons === undefined) { ffunc = new SMTLet("@vval", new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")]), new SMTIf(new SMTCallSimple("<", [new SMTVar("@vval"), new SMTConst("0")]), this.temitter.generateErrorResultAssert(ctype), this.temitter.generateResultTypeConstructorSuccess(ctype, new SMTVar("@vval"))) ); } else { ffunc = new SMTLet("@vval", new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")]), new SMTIf(new SMTCallSimple("<=", [new SMTConst("0"), new SMTVar("@vval")]), new SMTCallGeneral(cdecl.usingcons, [new SMTVar("@vval")]), this.temitter.generateErrorResultAssert(ctype) ) ); } } } else { if(primtype.typeID !== "NSCore::BigNat") { ffunc = this.temitter.generateResultTypeConstructorSuccess(ctype, new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")])); } else { ffunc = new SMTLet("@vval", new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")]), new SMTIf(new SMTCallSimple("<", [new SMTVar("@vval"), new SMTConst("0")]), this.temitter.generateErrorResultAssert(ctype), this.temitter.generateResultTypeConstructorSuccess(ctype, new SMTVar("@vval"))) ); } } if (ovfname !== undefined) { ffunc = new SMTIf( new SMTCallSimple(this.generateDesCallName(ltype, ovfname), [new SMTVar("l")]), ffunc, this.temitter.generateErrorResultAssert(ctype) ); } return { if: [new SMTFunction(this.generateDesCallName(ltype, "sum"), [{ vname: "l", vtype: ltype }], undefined, 0, restype, ffunc)], uf: ufops }; } //////// //StrConcat emitDestructorStrConcat(ltype: SMTType): SMTDestructorGenCode { const mirstrtype = this.temitter.getMIRType("NSCore::String"); const restype = this.temitter.generateResultType(mirstrtype); const ufconsname = "@UFStrConcatCons"; const ufops = [new SMTFunctionUninterpreted(this.generateDesCallName(ltype, ufconsname), [ltype], this.temitter.getSMTTypeFor(mirstrtype))]; const ffunc = this.temitter.generateResultTypeConstructorSuccess(mirstrtype, new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l")])); return { if: [new SMTFunction(this.generateDesCallName(ltype, "strconcat"), [{ vname: "l", vtype: ltype }], undefined, 0, restype, ffunc)], uf: ufops }; } //////// //StrJoin emitDestructorStrJoin(ltype: SMTType): SMTDestructorGenCode { const mirstrtype = this.temitter.getMIRType("NSCore::String"); const restype = this.temitter.generateResultType(mirstrtype); const ufconsname = "@UFStrJoinCons"; const ufops = [new SMTFunctionUninterpreted(this.generateDesCallName(ltype, ufconsname), [ltype, this.temitter.getSMTTypeFor(mirstrtype)], this.temitter.getSMTTypeFor(mirstrtype))]; const ffunc = this.temitter.generateResultTypeConstructorSuccess(mirstrtype, new SMTCallSimple(this.generateDesCallName(ltype, ufconsname), [new SMTVar("l"), new SMTVar("sep")])); return { if: [new SMTFunction(this.generateDesCallName(ltype, "strjoin"), [{ vname: "l", vtype: ltype }, { vname: "sep", vtype: this.temitter.getSMTTypeFor(mirstrtype) }], undefined, 0, restype, ffunc)], uf: ufops }; } private emitDestructorFindIndexOf_Shared(ltype: SMTType, isidx: boolean, code: string, pcode: MIRPCode, sl: SMTVar, osize: SMTVar, k: SMTExp): [SMTExp, SMTFunctionUninterpreted] { const [capturedargs, , ufpickargs] = this.generateCapturedInfoFor(pcode, isidx ? 2 : 1); const skloemcc = this.generateConsCallNameUsing(ltype, "skolem_list_index" + (isidx ? "_idx" : ""), code); const getop = this.generateDesCallName(ltype, "get"); const getcall = new SMTCallSimple(getop, [sl, new SMTVar("_@nn")]); const largs = isidx ? [getcall, new SMTVar("_@nn")] : [getcall]; const findidx = new SMTLet("_@nn", this.generateListIndexPickCall_Kth(skloemcc, sl, k, capturedargs), new SMTIf(new SMTCallSimple("bvult", [new SMTVar("_@nn"), osize]), new SMTIf(this.generateLambdaCallKnownSafe(code, this.temitter.getMIRType("NSCore::Bool"), largs, capturedargs), this.temitter.generateResultTypeConstructorSuccess(this.temitter.getMIRType("NSCore::Nat"), new SMTVar("_@nn")), this.temitter.generateErrorResultAssert(this.temitter.getMIRType("NSCore::Nat")) ), this.temitter.generateErrorResultAssert(this.temitter.getMIRType("NSCore::Nat")) ) ); return [ findidx, new SMTFunctionUninterpreted(skloemcc, [ltype, this.nattype, ...ufpickargs], this.nattype) ]; } private generateCapturedInfoFor(pcode: MIRPCode, k: number): [SMTVar[], {vname: string, vtype: SMTType}[], SMTType[]] { const lambdainfo = this.temitter.assembly.invokeDecls.get(pcode.code) as MIRInvokeBodyDecl; let capturedargs: SMTVar[] = []; let capturedparams: {vname: string, vtype: SMTType}[] = []; let ufpickargs: SMTType[] = []; lambdainfo.params.slice(k).forEach((p) => { capturedargs.push(new SMTVar(p.name)); capturedparams.push({vname: p.name, vtype: this.temitter.getSMTTypeFor(this.temitter.getMIRType(p.type))}); ufpickargs.push(this.temitter.getSMTTypeFor(this.temitter.getMIRType(p.type))); }); return [capturedargs, capturedparams, ufpickargs]; } private generateCapturedFieldInfoFor(ltype: SMTType, op: string, k: number, code: string, pcode: MIRPCode): { fname: string, ftype: SMTType }[] { const lambdainfo = this.temitter.assembly.invokeDecls.get(pcode.code) as MIRInvokeBodyDecl; const capturedfields = lambdainfo.params.slice(k).map((p) => { return { fname: this.generateULIFieldUsingFor(ltype, op, code, p.name), ftype: this.temitter.getSMTTypeFor(this.temitter.getMIRType(p.type)) } }); return capturedfields; } private generateCapturedFieldLetsInfoFor(ltype: SMTType, op: string, k: number, code: string, pcode: MIRPCode, ll: SMTVar): { vname: string, value: SMTExp }[] { const lambdainfo = this.temitter.assembly.invokeDecls.get(pcode.code) as MIRInvokeBodyDecl; const capturedfieldlets = lambdainfo.params.slice(k).map((p) => { return { vname: "c@" + p.name, value: this.generateGetULIFieldUsingFor(ltype, op, code, p.name, ll) }; }); return capturedfieldlets; } private processCapturedFieldLets(clets: { vname: string, value: SMTExp }[], continuation: SMTExp): SMTExp { if(clets.length === 0) { return continuation; } else { return new SMTLetMulti(clets, continuation); } } private generateListIndexPickCall_Kth(ctxname: string, sl: SMTVar, k: SMTExp, capturedargs: SMTVar[]): SMTExp { return new SMTCallSimple(ctxname, [sl, k, ...capturedargs]); } private generateLambdaCallKnownSafe(code: string, restype: MIRType, args: SMTExp[], cargs: SMTExp[]): SMTExp { if(this.safecalls.has(code)) { return new SMTCallSimple(this.temitter.lookupFunctionName(code), [...args, ...cargs]); } else { return this.temitter.generateResultGetSuccess(restype, new SMTCallGeneral(this.temitter.lookupFunctionName(code), [...args, ...cargs])); } } private generateLambdaCallGeneral(code: string, restype: MIRType, args: SMTExp[], cargs: SMTExp[]): SMTExp { return new SMTCallGeneral(this.temitter.lookupFunctionName(code), [...args, ...cargs]); } } export { ListOpsManager, ListOpsInfo, SMTConstructorGenCode, SMTDestructorGenCode };
the_stack
import ma = require('azure-pipelines-task-lib/mock-answer'); import tmrm = require('azure-pipelines-task-lib/mock-run'); import path = require('path'); import * as shared from './TestShared'; const DefaultBuildContext: string = shared.formatPath("a/w/**"); const DefaultDockerFileInput = shared.formatPath("a/w/**/Dockerfile"); const DefaultWorkingDirectory: string = shared.formatPath("a/w"); const DockerfilePath: string = shared.formatPath("a/w/Dockerfile"); const BuildctlDockerfilePath: string = `"F:\\a\\w\\meta\\"`; const BuildctlContextPath: string = `"F:\\a\\w\\context"`; const DockerfilePath2: string = shared.formatPath("a/w/meta/Dockerfile"); const BuildContextPath: string = shared.formatPath("a/w"); const BuildContextPath2: string = shared.formatPath("a/w/context"); const BuildContextPath3: string = shared.formatPath("a/w/context"); const Dockerfile: string = `FROM ubuntu\nCMD ["echo","Hello World!"]` let taskPath = path.join(__dirname, '../src', 'buildcontainer.js'); let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath); var nock = require("nock"); tr.setInput('dockerRegistryServiceConnection', process.env[shared.TestEnvVars.dockerRegistryServiceConnection] || ""); tr.setInput('repository', process.env[shared.TestEnvVars.repository] || ""); tr.setInput('Dockerfile', process.env[shared.TestEnvVars.dockerFile] || DefaultDockerFileInput); tr.setInput('buildContext', process.env[shared.TestEnvVars.buildContext] || DefaultBuildContext); tr.setInput('tags', process.env[shared.TestEnvVars.tags] || "11"); console.log("Inputs have been set"); process.env["RELEASE_RELEASENAME"] = "Release-1"; process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"] = DefaultWorkingDirectory; process.env["SYSTEM_HOSTTYPE"] = process.env[shared.TestEnvVars.hostType] || shared.HostTypes.build; process.env["SYSTEM_SERVERTYPE"] = "hosted"; process.env["ENDPOINT_AUTH_dockerhubendpoint"] = "{\"parameters\":{\"username\":\"testuser\", \"password\":\"regpassword\", \"email\":\"testuser1@microsoft.com\",\"registry\":\"https://index.docker.io/v1/\"},\"scheme\":\"UsernamePassword\"}"; // Docker registry endpoint with ACR registrytype process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint_serviceprincipalid"] = "testspn"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint_serviceprincipalkey"] = "acrspnkey"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint_loginServer"] = "https://testacr.azurecr.io"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint_scheme"] = "ServicePrincipal"; process.env["ENDPOINT_DATA_acrendpoint_registryType"] = "ACR"; // Docker registry endpoint with ACR registrytype containing uppercase characters in registry URL process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint2_serviceprincipalid"] = "testspn2"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint2_serviceprincipalkey"] = "acrspnkey2"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint2_loginServer"] = "https://testAcr2.azurecr.io"; process.env["ENDPOINT_AUTH_PARAMETER_acrendpoint2_scheme"] = "ServicePrincipal"; process.env["ENDPOINT_DATA_acrendpoint2_registryType"] = "ACR"; // Set variables used for common labels process.env["SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"] = shared.SharedValues.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI; process.env["SYSTEM_TEAMPROJECT"] = shared.SharedValues.SYSTEM_TEAMPROJECT; // Set variables used for build labels process.env["BUILD_REPOSITORY_NAME"] = process.env["SYSTEM_HOSTTYPE"] == shared.HostTypes.build ? shared.SharedValues.BUILD_REPOSITORY_NAME : ""; process.env["BUILD_REPOSITORY_URI"] = shared.SharedValues.BUILD_REPOSITORY_URI; process.env["BUILD_SOURCEBRANCHNAME"] = shared.SharedValues.BUILD_SOURCEBRANCHNAME; process.env["BUILD_SOURCEVERSION"] = shared.SharedValues.BUILD_SOURCEVERSION; process.env["BUILD_DEFINITIONNAME"] = shared.SharedValues.BUILD_DEFINITIONNAME; process.env["BUILD_BUILDNUMBER"] = shared.SharedValues.BUILD_BUILDNUMBER; process.env["BUILD_BUILDURI"] = shared.SharedValues.BUILD_BUILDURI; // Set variables used for release labels process.env["RELEASE_DEFINITIONNAME"] = shared.SharedValues.RELEASE_DEFINITIONNAME; process.env["RELEASE_RELEASEID"] = shared.SharedValues.RELEASE_RELEASEID; process.env["RELEASE_RELEASEWEBURL"] = shared.SharedValues.RELEASE_RELEASEWEBURL; // provide answers for task mock let a = { "which": { "docker": "docker", "buildctl": "buildctl", "kubectl": "kubectl", "img":"img" }, "checkPath": { "docker": true, "buildctl": true, "kubectl": true, "img": true }, "exist": { "docker": true, "buildctl": true, "kubectl": true, "img": true }, "exec": { "docker push test/test:2" : { "code": 0, "stdout": "successfully pushed test/test:2 image" }, "buildctl --help" : { "code": 0, "stdout": "successfully displayed help output" }, "kubectl get service azure-pipelines-pool -o=json" : { "code": 0, "stdout": "{\"metadata\": {\"namespace\": \"azuredevops\"},\"spec\": {\"clusterIP\": \"10.0.11.12\"},\"status\": {\"loadBalancer\": {\"ingress\": [{\"ip\": \"testip\"}]}}}" }, "kubectl get pods -l=role=buildkit -o=json" : { "code": 0, "stdout": "{\"apiVersion\": \"v1\",\"items\": [{\"apiVersion\": \"v1\",\"kind\": \"Pod\",\"metadata\": {\"name\": \"buildkitd-0\",\"namespace\": \"azd\"}},{\"apiVersion\": \"v1\",\"kind\": \"Pod\",\"metadata\": {\"name\": \"buildkitd-1\",\"namespace\": \"azd\"}},{\"apiVersion\": \"v1\",\"kind\": \"Pod\",\"metadata\": {\"name\": \"buildkitd-2\",\"namespace\": \"azd\"}}],\"kind\": \"List\"}" }, "kubectl get service azure-pipelines-pool-custom -o=json" : { "code": 0, "stdout": "{\"metadata\": {\"namespace\": \"azuredevops\"},\"spec\": {\"ports\": [{\"port\": 8080}]},\"status\": {\"loadBalancer\": {\"ingress\": [{\"ip\": \"testip\"}]}}}" } }, "find": {} }; nock('http://10.0.11.12') .get('/buildPod') .reply(201, { status: 'success', Message: 'buildkitd-0' }).persist(); // Add extra answer definitions that need to be dynamically generated a.exist[DockerfilePath] = true; a.exist[DockerfilePath2] = true; a.find[`${DefaultWorkingDirectory}`] = [ `${DockerfilePath}` ] a.exec[`buildctl build --frontend=dockerfile.v0 --local=context=F:\\a\\w\\context --local=dockerfile=F:\\a\\w\\meta\\`] = { "code": 0, "stdout": "successfully built image using buildctl" }; a.exec[`docker build -f ${DockerfilePath} -t testacr.azurecr.io/testrepo:11 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image and tagged testacr.azurecr.io/testuser/testrepo:11." }; a.exec[`docker build -f ${DockerfilePath} -t testacr2.azurecr.io/testrepo:11 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image and tagged testacr2.azurecr.io/testuser/testrepo:11." }; a.exec[`docker build -f ${DockerfilePath} -t testuser/testrepo:tag1 -t testuser/testrepo:tag2 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image and tagged testuser/testrepo:tag1 and testuser/testrepo:tag2." }; a.exec[`docker build -f ${DockerfilePath} -t testuser/testrepo:tag1 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image using docker and tagged testuser/testrepo:tag1" }; a.exec[`docker build -f ${DockerfilePath} ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image using docker" }; a.exec[`docker build -f ${DockerfilePath} -t testuser/testrepo:11 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image and tagged testuser/testrepo:11." }; a.exec[`docker build -f ${DockerfilePath2} -t testuser/testrepo:11 ${BuildContextPath2}`] = { "code": 0, "stdout": "successfully built image and tagged testuser/testrepo:11." }; a.exec[`docker build -f ${DockerfilePath} -t testuser/testrepo:11 ${BuildContextPath3}`] = { "code": 0, "stdout": "successfully built image and tagged testuser/testrepo:11." }; a.exec[`docker build -f ${DockerfilePath} -t testuser/testrepo:11 ${BuildContextPath}`] = { "code": 0, "stdout": "successfully built image and tagged testuser/testrepo:11." }; a.exec[`docker push testuser/testrepo:11`] = { "code": 0, "stdout": "successfully pushed testuser/testrepo:11." }; a.exec[`docker push testacr.azurecr.io/testrepo:11`] = { "code": 0, "stdout": "successfully pushed testacr.azurecr.io/testrepo:11." }; a.exec[`docker push testacr2.azurecr.io/testrepo:11`] = { "code": 0, "stdout": "successfully pushed testacr.azurecr.io/testrepo:11." }; a.exec[`docker push testuser/testrepo:tag1`] = { "code": 0, "stdout": "successfully pushed testuser/testrepo:tag1." }; a.exec[`docker push testuser/testrepo:tag2`] = { "code": 0, "stdout": "successfully pushed testuser/testrepo:tag2." }; a.exec[`buildctl build --frontend=dockerfile.v0 --local=context=F:\\a\\w\\context --local=dockerfile=F:\\a\\w\\meta\\ --exporter=image --exporter-opt=name=testuser/testrepo:11 --exporter-opt=push=true`] = { "code": 0, "stdout": "successfully built and pushed image using buildctl" }; a.exec[`buildctl build --frontend=dockerfile.v0 --local=context=F:\\a\\w\\** --local=dockerfile=F:\\a\\w\\**\\ --exporter=image --exporter-opt=name=testuser/testrepo:tag1,testuser/testrepo:tag2 --exporter-opt=push=true`] = { "code": 0, "stdout": "successfully built and pushed image using buildctl with multiple tags" }; a.exec[`buildctl build --frontend=dockerfile.v0 --local=context=F:\\a\\w\\** --local=dockerfile=F:\\a\\w\\**\\ --exporter=image --exporter-opt=name=testacr.azurecr.io/testrepo:11 --exporter-opt=push=true`] = { "code": 0, "stdout": "successfully built and pushed image using buildctl for acr" }; tr.setAnswers(<any>a); // Create mock for fs module. Required to make the base image name extraction (push command) work. let fs = require('fs'); let fsClone = Object.assign({}, fs); fsClone.readFileSync = function(filePath, options) { switch (filePath) { case DockerfilePath: case DockerfilePath2: return Dockerfile; default: return fs.readFileSync(filePath, options); } }; tr.registerMock('fs', fsClone); tr.run();
the_stack
import * as assert from 'assert'; import { SnippetCompletion, SnippetCompletionProvider } from 'vs/workbench/contrib/snippets/browser/snippetCompletionProvider'; import { Position } from 'vs/editor/common/core/position'; import { createModelServices, instantiateTextModel } from 'vs/editor/test/common/testTextModel'; import { ISnippetsService } from 'vs/workbench/contrib/snippets/browser/snippets.contribution'; import { Snippet, SnippetSource } from 'vs/workbench/contrib/snippets/browser/snippetsFile'; import { CompletionContext, CompletionItemLabel, CompletionItemRanges, CompletionTriggerKind } from 'vs/editor/common/languages'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { ILanguageService } from 'vs/editor/common/languages/language'; class SimpleSnippetService implements ISnippetsService { declare readonly _serviceBrand: undefined; constructor(readonly snippets: Snippet[]) { } getSnippets() { return Promise.resolve(this.getSnippetsSync()); } getSnippetsSync(): Snippet[] { return this.snippets; } getSnippetFiles(): any { throw new Error(); } isEnabled(): boolean { throw new Error(); } updateEnablement(): void { throw new Error(); } } suite('SnippetsService', function () { const context: CompletionContext = { triggerKind: CompletionTriggerKind.Invoke }; let disposables: DisposableStore; let instantiationService: TestInstantiationService; let languageService: ILanguageService; let snippetService: ISnippetsService; setup(function () { disposables = new DisposableStore(); instantiationService = createModelServices(disposables); languageService = instantiationService.get(ILanguageService); disposables.add(languageService.registerLanguage({ id: 'fooLang', extensions: ['.fooLang',] })); snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'barTest', 'bar', '', 'barCodeSnippet', '', SnippetSource.User ), new Snippet( ['fooLang'], 'bazzTest', 'bazz', '', 'bazzCodeSnippet', '', SnippetSource.User )]); }); teardown(() => { disposables.dispose(); }); test('snippet completions - simple', function () { const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); const model = disposables.add(instantiateTextModel(instantiationService, '', 'fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 2); }); }); test('snippet completions - simple 2', async function () { const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); const model = disposables.add(instantiateTextModel(instantiationService, 'hello ', 'fooLang')); await provider.provideCompletionItems(model, new Position(1, 6) /* hello| */, context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 0); }); await provider.provideCompletionItems(model, new Position(1, 7) /* hello |*/, context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 2); }); }); test('snippet completions - with prefix', function () { const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); const model = disposables.add(instantiateTextModel(instantiationService, 'bar', 'fooLang')); return provider.provideCompletionItems(model, new Position(1, 4), context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 1); assert.deepStrictEqual(result.suggestions[0].label, { label: 'bar', description: 'barTest' }); assert.strictEqual((result.suggestions[0].range as any).insert.startColumn, 1); assert.strictEqual(result.suggestions[0].insertText, 'barCodeSnippet'); }); }); test('snippet completions - with different prefixes', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'barTest', 'bar', '', 's1', '', SnippetSource.User ), new Snippet( ['fooLang'], 'name', 'bar-bar', '', 's2', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); const model = disposables.add(instantiateTextModel(instantiationService, 'bar-bar', 'fooLang')); await provider.provideCompletionItems(model, new Position(1, 3), context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 2); assert.deepStrictEqual(result.suggestions[0].label, { label: 'bar', description: 'barTest' }); assert.strictEqual(result.suggestions[0].insertText, 's1'); assert.strictEqual((result.suggestions[0].range as CompletionItemRanges).insert.startColumn, 1); assert.deepStrictEqual(result.suggestions[1].label, { label: 'bar-bar', description: 'name' }); assert.strictEqual(result.suggestions[1].insertText, 's2'); assert.strictEqual((result.suggestions[1].range as CompletionItemRanges).insert.startColumn, 1); }); await provider.provideCompletionItems(model, new Position(1, 5), context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 2); const [first, second] = result.suggestions; assert.deepStrictEqual(first.label, { label: 'bar', description: 'barTest' }); assert.strictEqual(first.insertText, 's1'); assert.strictEqual((first.range as CompletionItemRanges).insert.startColumn, 5); assert.deepStrictEqual(second.label, { label: 'bar-bar', description: 'name' }); assert.strictEqual(second.insertText, 's2'); assert.strictEqual((second.range as CompletionItemRanges).insert.startColumn, 1); }); await provider.provideCompletionItems(model, new Position(1, 6), context)!.then(result => { assert.strictEqual(result.incomplete, undefined); assert.strictEqual(result.suggestions.length, 2); assert.deepStrictEqual(result.suggestions[0].label, { label: 'bar', description: 'barTest' }); assert.strictEqual(result.suggestions[0].insertText, 's1'); assert.strictEqual((result.suggestions[0].range as any).insert.startColumn, 5); assert.deepStrictEqual(result.suggestions[1].label, { label: 'bar-bar', description: 'name' }); assert.strictEqual(result.suggestions[1].insertText, 's2'); assert.strictEqual((result.suggestions[1].range as any).insert.startColumn, 1); }); }); test('Cannot use "<?php" as user snippet prefix anymore, #26275', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], '', '<?php', '', 'insert me', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, '\t<?php', 'fooLang'); return provider.provideCompletionItems(model, new Position(1, 7), context)!.then(result => { assert.strictEqual(result.suggestions.length, 1); model.dispose(); model = instantiateTextModel(instantiationService, '\t<?', 'fooLang'); return provider.provideCompletionItems(model, new Position(1, 4), context)!; }).then(result => { assert.strictEqual(result.suggestions.length, 1); assert.strictEqual((result.suggestions[0].range as any).insert.startColumn, 2); model.dispose(); model = instantiateTextModel(instantiationService, 'a<?', 'fooLang'); return provider.provideCompletionItems(model, new Position(1, 4), context)!; }).then(result => { assert.strictEqual(result.suggestions.length, 1); assert.strictEqual((result.suggestions[0].range as any).insert.startColumn, 2); model.dispose(); }); }); test('No user snippets in suggestions, when inside the code, #30508', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], '', 'foo', '', '<foo>$0</foo>', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, '<head>\n\t\n>/head>', 'fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.strictEqual(result.suggestions.length, 1); return provider.provideCompletionItems(model, new Position(2, 2), context)!; }).then(result => { assert.strictEqual(result.suggestions.length, 1); }); }); test('SnippetSuggest - ensure extension snippets come last ', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'second', 'second', '', 'second', '', SnippetSource.Extension ), new Snippet( ['fooLang'], 'first', 'first', '', 'first', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, '', 'fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.strictEqual(result.suggestions.length, 2); let [first, second] = result.suggestions; assert.deepStrictEqual(first.label, { label: 'first', description: 'first' }); assert.deepStrictEqual(second.label, { label: 'second', description: 'second' }); }); }); test('Dash in snippets prefix broken #53945', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'p-a', 'p-a', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, 'p-', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.strictEqual(result.suggestions.length, 1); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); }); test('No snippets suggestion on long lines beyond character 100 #58807', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, 'Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea b', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 158), context)!; assert.strictEqual(result.suggestions.length, 1); }); test('Type colon will trigger snippet #60746', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, ':', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.strictEqual(result.suggestions.length, 0); }); test('substring of prefix can\'t trigger snippet #60737', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'mytemplate', 'mytemplate', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, 'template', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 9), context)!; assert.strictEqual(result.suggestions.length, 1); assert.deepStrictEqual(result.suggestions[0].label, { label: 'mytemplate', description: 'mytemplate' }); }); test('No snippets suggestion beyond character 100 if not at end of line #60247', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, 'Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea b text_after_b', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 158), context)!; assert.strictEqual(result.suggestions.length, 1); }); test('issue #61296: VS code freezes when editing CSS file with emoji', async function () { const languageConfigurationService = new TestLanguageConfigurationService(); disposables.add(languageConfigurationService.register('fooLang', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g })); snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', '-a-bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, languageConfigurationService); let model = disposables.add(instantiateTextModel(instantiationService, '.🐷-a-b', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 8), context)!; assert.strictEqual(result.suggestions.length, 1); }); test('No snippets shown when triggering completions at whitespace on line that already has text #62335', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = disposables.add(instantiateTextModel(instantiationService, 'a ', 'fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); }); test('Snippet prefix with special chars and numbers does not work #62906', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'noblockwdelay', '<<', '', '<= #dly"', '', SnippetSource.User ), new Snippet( ['fooLang'], 'noblockwdelay', '11', '', 'eleven', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, ' <', 'fooLang'); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); let [first] = result.suggestions; assert.strictEqual((first.range as any).insert.startColumn, 2); model.dispose(); model = instantiateTextModel(instantiationService, '1', 'fooLang'); result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.strictEqual(result.suggestions.length, 1); [first] = result.suggestions; assert.strictEqual((first.range as any).insert.startColumn, 1); model.dispose(); }); test('Snippet replace range', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'notWordTest', 'not word', '', 'not word snippet', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, 'not wordFoo bar', 'fooLang'); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); let [first] = result.suggestions; assert.strictEqual((first.range as any).insert.endColumn, 3); assert.strictEqual((first.range as any).replace.endColumn, 9); model.dispose(); model = instantiateTextModel(instantiationService, 'not woFoo bar', 'fooLang'); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.strictEqual(result.suggestions.length, 1); [first] = result.suggestions; assert.strictEqual((first.range as any).insert.endColumn, 3); assert.strictEqual((first.range as any).replace.endColumn, 3); model.dispose(); model = instantiateTextModel(instantiationService, 'not word', 'fooLang'); result = await provider.provideCompletionItems(model, new Position(1, 1), context)!; assert.strictEqual(result.suggestions.length, 1); [first] = result.suggestions; assert.strictEqual((first.range as any).insert.endColumn, 1); assert.strictEqual((first.range as any).replace.endColumn, 9); model.dispose(); }); test('Snippet replace-range incorrect #108894', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'eng', 'eng', '', '<span></span>', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, 'filler e KEEP ng filler', 'fooLang'); let result = await provider.provideCompletionItems(model, new Position(1, 9), context)!; assert.strictEqual(result.suggestions.length, 1); let [first] = result.suggestions; assert.strictEqual((first.range as any).insert.endColumn, 9); assert.strictEqual((first.range as any).replace.endColumn, 9); model.dispose(); }); test('Snippet will replace auto-closing pair if specified in prefix', async function () { const languageConfigurationService = new TestLanguageConfigurationService(); disposables.add(languageConfigurationService.register('fooLang', { brackets: [ ['{', '}'], ['[', ']'], ['(', ')'], ] })); snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'PSCustomObject', '[PSCustomObject]', '', '[PSCustomObject] @{ Key = Value }', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, languageConfigurationService); let model = instantiateTextModel(instantiationService, '[psc]', 'fooLang'); let result = await provider.provideCompletionItems(model, new Position(1, 5), context)!; assert.strictEqual(result.suggestions.length, 1); let [first] = result.suggestions; assert.strictEqual((first.range as any).insert.endColumn, 5); // This is 6 because it should eat the `]` at the end of the text even if cursor is before it assert.strictEqual((first.range as any).replace.endColumn, 6); model.dispose(); }); test('Leading whitespace in snippet prefix #123860', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'cite-name', ' cite', '', '~\\cite{$CLIPBOARD}', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, ' ci', 'fooLang'); let result = await provider.provideCompletionItems(model, new Position(1, 4), context)!; assert.strictEqual(result.suggestions.length, 1); let [first] = result.suggestions; assert.strictEqual((<CompletionItemLabel>first.label).label, ' cite'); assert.strictEqual((<CompletionItemRanges>first.range).insert.startColumn, 1); model.dispose(); }); test('still show suggestions in string when disable string suggestion #136611', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'aaa', 'aaa', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], 'bbb', 'bbb', '', 'value', '', SnippetSource.User), // new Snippet(['fooLang'], '\'ccc', '\'ccc', '', 'value', '', SnippetSource.User) ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, '\'\'', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 2), { triggerKind: CompletionTriggerKind.TriggerCharacter, triggerCharacter: '\'' } )!; assert.strictEqual(result.suggestions.length, 0); model.dispose(); }); test('still show suggestions in string when disable string suggestion #136611', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'aaa', 'aaa', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], 'bbb', 'bbb', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], '\'ccc', '\'ccc', '', 'value', '', SnippetSource.User) ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, '\'\'', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 2), { triggerKind: CompletionTriggerKind.TriggerCharacter, triggerCharacter: '\'' } )!; assert.strictEqual(result.suggestions.length, 1); model.dispose(); }); test('Snippet suggestions are too eager #138707 (word)', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'tys', 'tys', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], 'hell_or_tell', 'hell_or_tell', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], '^y', '^y', '', 'value', '', SnippetSource.User), ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, '\'hellot\'', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 8), { triggerKind: CompletionTriggerKind.Invoke } )!; assert.strictEqual(result.suggestions.length, 1); assert.strictEqual((<SnippetCompletion>result.suggestions[0]).label.label, 'hell_or_tell'); model.dispose(); }); test('Snippet suggestions are too eager #138707 (no word)', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'tys', 'tys', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], 't', 't', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], '^y', '^y', '', 'value', '', SnippetSource.User), ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, ')*&^', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 5), { triggerKind: CompletionTriggerKind.Invoke } )!; assert.strictEqual(result.suggestions.length, 1); assert.strictEqual((<SnippetCompletion>result.suggestions[0]).label.label, '^y'); model.dispose(); }); test('Snippet suggestions are too eager #138707 (word/word)', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'async arrow function', 'async arrow function', '', 'value', '', SnippetSource.User), new Snippet(['fooLang'], 'foobarrrrrr', 'foobarrrrrr', '', 'value', '', SnippetSource.User), ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, 'foobar', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 7), { triggerKind: CompletionTriggerKind.Invoke } )!; assert.strictEqual(result.suggestions.length, 1); assert.strictEqual((<SnippetCompletion>result.suggestions[0]).label.label, 'foobarrrrrr'); model.dispose(); }); test('Strange and useless autosuggestion #region/#endregion PHP #140039', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'reg', '#region', '', 'value', '', SnippetSource.User), ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, 'function abc(w)', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 15), { triggerKind: CompletionTriggerKind.Invoke } )!; assert.strictEqual(result.suggestions.length, 0); model.dispose(); }); test.skip('Snippets disappear with . key #145960', async function () { snippetService = new SimpleSnippetService([ new Snippet(['fooLang'], 'div', 'div', '', 'div', '', SnippetSource.User), new Snippet(['fooLang'], 'div.', 'div.', '', 'div.', '', SnippetSource.User), new Snippet(['fooLang'], 'div#', 'div#', '', 'div#', '', SnippetSource.User), ]); const provider = new SnippetCompletionProvider(languageService, snippetService, new TestLanguageConfigurationService()); let model = instantiateTextModel(instantiationService, 'di', 'fooLang'); let result = await provider.provideCompletionItems( model, new Position(1, 3), { triggerKind: CompletionTriggerKind.Invoke } )!; assert.strictEqual(result.suggestions.length, 3); model.applyEdits([EditOperation.insert(new Position(1, 3), '.')]); assert.strictEqual(model.getValue(), 'di.'); let result2 = await provider.provideCompletionItems( model, new Position(1, 4), { triggerKind: CompletionTriggerKind.TriggerCharacter, triggerCharacter: '.' } )!; assert.strictEqual(result2.suggestions.length, 1); assert.strictEqual(result2.suggestions[0].insertText, 'div.'); model.dispose(); }); });
the_stack
/// <reference path="jqwidgets.d.ts" /> import '../jqwidgets/jqxcore.js'; import '../jqwidgets/jqxtooltip.js'; import '../jqwidgets/jqxpasswordinput.js'; import { Component, Input, Output, EventEmitter, ElementRef, forwardRef, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; const noop = () => { }; declare let JQXLite: any; const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => jqxPasswordInputComponent), multi: true } @Component({ selector: 'jqxPasswordInput', template: '<input type="password" [(ngModel)]="ngValue">', providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush }) export class jqxPasswordInputComponent implements ControlValueAccessor, OnChanges { @Input('disabled') attrDisabled: boolean; @Input('localization') attrLocalization: jqwidgets.PasswordInputLocalization; @Input('maxLength') attrMaxLength: number | string; @Input('placeHolder') attrPlaceHolder: number | string; @Input('passwordStrength') attrPasswordStrength: (password:jqwidgets.PasswordInputPasswordStrength['password'], characters:jqwidgets.PasswordInputPasswordStrength['characters'], defaultStrength:jqwidgets.PasswordInputPasswordStrength['defaultStrength']) => string; @Input('rtl') attrRtl: boolean; @Input('strengthColors') attrStrengthColors: jqwidgets.PasswordInputStrengthColors; @Input('showStrength') attrShowStrength: boolean; @Input('showStrengthPosition') attrShowStrengthPosition: string; @Input('strengthTypeRenderer') attrStrengthTypeRenderer: (password:jqwidgets.PasswordInputStrengthTypeRenderer['password'], characters:jqwidgets.PasswordInputStrengthTypeRenderer['characters'], defaultStrength:jqwidgets.PasswordInputStrengthTypeRenderer['defaultStrength']) => string; @Input('showPasswordIcon') attrShowPasswordIcon: boolean; @Input('theme') attrTheme: string; @Input('width') attrWidth: string | number; @Input('height') attrHeight: string | number; @Input('auto-create') autoCreate: boolean = true; properties: string[] = ['disabled','height','localization','maxLength','placeHolder','passwordStrength','rtl','strengthColors','showStrength','showStrengthPosition','strengthTypeRenderer','showPasswordIcon','theme','width']; host: any; elementRef: ElementRef; widgetObject: jqwidgets.jqxPasswordInput; private onTouchedCallback: () => void = noop; private onChangeCallback: (_: any) => void = noop; constructor(containerElement: ElementRef) { this.elementRef = containerElement; } ngOnInit() { if (this.autoCreate) { this.createComponent(); } }; ngOnChanges(changes: SimpleChanges) { if (this.host) { for (let i = 0; i < this.properties.length; i++) { let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1); let areEqual: boolean = false; if (this[attrName] !== undefined) { if (typeof this[attrName] === 'object') { if (this[attrName] instanceof Array) { areEqual = this.arraysEqual(this[attrName], this.host.jqxPasswordInput(this.properties[i])); } if (areEqual) { return false; } this.host.jqxPasswordInput(this.properties[i], this[attrName]); continue; } if (this[attrName] !== this.host.jqxPasswordInput(this.properties[i])) { this.host.jqxPasswordInput(this.properties[i], this[attrName]); } } } } } arraysEqual(attrValue: any, hostValue: any): boolean { if ((attrValue && !hostValue) || (!attrValue && hostValue)) { return false; } if (attrValue.length != hostValue.length) { return false; } for (let i = 0; i < attrValue.length; i++) { if (attrValue[i] !== hostValue[i]) { return false; } } return true; } manageAttributes(): any { let options = {}; for (let i = 0; i < this.properties.length; i++) { let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1); if (this[attrName] !== undefined) { options[this.properties[i]] = this[attrName]; } } return options; } moveClasses(parentEl: HTMLElement, childEl: HTMLElement): void { let classes: any = parentEl.classList; if (classes.length > 0) { childEl.classList.add(...classes); } parentEl.className = ''; } moveStyles(parentEl: HTMLElement, childEl: HTMLElement): void { let style = parentEl.style.cssText; childEl.style.cssText = style parentEl.style.cssText = ''; } createComponent(options?: any): void { if (this.host) { return; } if (options) { JQXLite.extend(options, this.manageAttributes()); } else { options = this.manageAttributes(); } this.host = JQXLite(this.elementRef.nativeElement.firstChild); this.moveClasses(this.elementRef.nativeElement, this.host[0]); this.moveStyles(this.elementRef.nativeElement, this.host[0]); this.__wireEvents__(); this.widgetObject = jqwidgets.createInstance(this.host, 'jqxPasswordInput', options); } createWidget(options?: any): void { this.createComponent(options); } __updateRect__() : void { if(this.host) this.host.css({ width: this.attrWidth, height: this.attrHeight }); } get ngValue(): any { if (this.widgetObject) { const value = this.host.val(); return value; } return ''; } set ngValue(value: any) { if (this.widgetObject) { this.onChangeCallback(value); } } writeValue(value: any): void { if(this.widgetObject) { this.host.jqxPasswordInput('val', value); } if (this.host && (value === null || value === undefined)) { this.host.jqxPasswordInput('val', ''); } } registerOnChange(fn: any): void { this.onChangeCallback = fn; } registerOnTouched(fn: any): void { this.onTouchedCallback = fn; } setOptions(options: any) : void { this.host.jqxPasswordInput('setOptions', options); } // jqxPasswordInputComponent properties disabled(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxPasswordInput('disabled', arg); } else { return this.host.jqxPasswordInput('disabled'); } } height(arg?: string | number): string | number { if (arg !== undefined) { this.host.jqxPasswordInput('height', arg); } else { return this.host.jqxPasswordInput('height'); } } localization(arg?: jqwidgets.PasswordInputLocalization): jqwidgets.PasswordInputLocalization { if (arg !== undefined) { this.host.jqxPasswordInput('localization', arg); } else { return this.host.jqxPasswordInput('localization'); } } maxLength(arg?: number | string): number | string { if (arg !== undefined) { this.host.jqxPasswordInput('maxLength', arg); } else { return this.host.jqxPasswordInput('maxLength'); } } placeHolder(arg?: number | string): number | string { if (arg !== undefined) { this.host.jqxPasswordInput('placeHolder', arg); } else { return this.host.jqxPasswordInput('placeHolder'); } } passwordStrength(arg?: (password:jqwidgets.PasswordInputPasswordStrength['password'], characters:jqwidgets.PasswordInputPasswordStrength['characters'], defaultStrength:jqwidgets.PasswordInputPasswordStrength['defaultStrength']) => string): (password:jqwidgets.PasswordInputPasswordStrength['password'], characters:jqwidgets.PasswordInputPasswordStrength['characters'], defaultStrength:jqwidgets.PasswordInputPasswordStrength['defaultStrength']) => string { if (arg !== undefined) { this.host.jqxPasswordInput('passwordStrength', arg); } else { return this.host.jqxPasswordInput('passwordStrength'); } } rtl(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxPasswordInput('rtl', arg); } else { return this.host.jqxPasswordInput('rtl'); } } strengthColors(arg?: jqwidgets.PasswordInputStrengthColors): jqwidgets.PasswordInputStrengthColors { if (arg !== undefined) { this.host.jqxPasswordInput('strengthColors', arg); } else { return this.host.jqxPasswordInput('strengthColors'); } } showStrength(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxPasswordInput('showStrength', arg); } else { return this.host.jqxPasswordInput('showStrength'); } } showStrengthPosition(arg?: string): string { if (arg !== undefined) { this.host.jqxPasswordInput('showStrengthPosition', arg); } else { return this.host.jqxPasswordInput('showStrengthPosition'); } } strengthTypeRenderer(arg?: (password:jqwidgets.PasswordInputStrengthTypeRenderer['password'], characters:jqwidgets.PasswordInputStrengthTypeRenderer['characters'], defaultStrength:jqwidgets.PasswordInputStrengthTypeRenderer['defaultStrength']) => string): (password:jqwidgets.PasswordInputStrengthTypeRenderer['password'], characters:jqwidgets.PasswordInputStrengthTypeRenderer['characters'], defaultStrength:jqwidgets.PasswordInputStrengthTypeRenderer['defaultStrength']) => string { if (arg !== undefined) { this.host.jqxPasswordInput('strengthTypeRenderer', arg); } else { return this.host.jqxPasswordInput('strengthTypeRenderer'); } } showPasswordIcon(arg?: boolean): boolean { if (arg !== undefined) { this.host.jqxPasswordInput('showPasswordIcon', arg); } else { return this.host.jqxPasswordInput('showPasswordIcon'); } } theme(arg?: string): string { if (arg !== undefined) { this.host.jqxPasswordInput('theme', arg); } else { return this.host.jqxPasswordInput('theme'); } } width(arg?: string | number): string | number { if (arg !== undefined) { this.host.jqxPasswordInput('width', arg); } else { return this.host.jqxPasswordInput('width'); } } // jqxPasswordInputComponent functions render(): void { this.host.jqxPasswordInput('render'); } refresh(): void { this.host.jqxPasswordInput('refresh'); } val(value?: string): any { if (value !== undefined) { return this.host.jqxPasswordInput('val', value); } else { return this.host.jqxPasswordInput('val'); } }; // jqxPasswordInputComponent events @Output() onChange = new EventEmitter(); __wireEvents__(): void { this.host.on('change', (eventData: any) => { this.onChange.emit(eventData); }); } } //jqxPasswordInputComponent
the_stack
import { DirectiveWrapper, InvalidDirectiveError, MappingTemplate, SyncConfig, SyncUtils, TransformerModelBase, TransformerNestedStack, FieldWrapper, InputObjectDefinitionWrapper, ObjectDefinitionWrapper, } from '@aws-amplify/graphql-transformer-core'; import { AppSyncDataSourceType, DataSourceInstance, DataSourceProvider, MutationFieldType, QueryFieldType, SubscriptionFieldType, TransformerContextProvider, TransformerModelProvider, TransformerPrepareStepContextProvider, TransformerResolverProvider, TransformerSchemaVisitStepContextProvider, TransformerTransformSchemaStepContextProvider, TransformerValidationStepContextProvider, TransformerBeforeStepContextProvider, } from '@aws-amplify/graphql-transformer-interfaces'; import { AttributeType, CfnTable, ITable, StreamViewType, Table, TableEncryption } from '@aws-cdk/aws-dynamodb'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import { CfnDataSource } from '@aws-cdk/aws-appsync'; import { DirectiveNode, FieldDefinitionNode, InputObjectTypeDefinitionNode, InputValueDefinitionNode, ObjectTypeDefinitionNode, } from 'graphql'; import { getBaseType, isScalar, makeArgument, makeDirective, makeField, makeInputValueDefinition, makeNamedType, makeNonNullType, makeValueNode, ModelResourceIDs, plurality, ResolverResourceIDs, ResourceConstants, SyncResourceIDs, toCamelCase, toPascalCase, } from 'graphql-transformer-common'; import { addDirectivesToOperation, addModelConditionInputs, createEnumModelFilters, extendTypeWithDirectives, makeCreateInputField, makeDeleteInputField, makeListQueryFilterInput, makeListQueryModel, makeModelSortDirectionEnumObject, makeMutationConditionInput, makeUpdateInputField, propagateApiKeyToNestedTypes, } from './graphql-types'; import { generateAuthExpressionForSandboxMode, generateCreateInitSlotTemplate, generateCreateRequestTemplate, generateDefaultResponseMappingTemplate, generateDeleteRequestTemplate, generateResolverKey, generateSubscriptionRequestTemplate, generateSubscriptionResponseTemplate, generateUpdateInitSlotTemplate, generateUpdateRequestTemplate, } from './resolvers'; import { generateGetRequestTemplate, generateGetResponseTemplate, generateListRequestTemplate, generateSyncRequestTemplate, } from './resolvers/query'; import { CfnRole } from '@aws-cdk/aws-iam'; import md5 from 'md5'; import { API_KEY_DIRECTIVE } from './definitions'; export type Nullable<T> = T | null; export type OptionalAndNullable<T> = Partial<T>; export enum SubscriptionLevel { off = 'off', public = 'public', on = 'on', } export type ModelDirectiveConfiguration = { queries?: OptionalAndNullable<{ get: OptionalAndNullable<string>; list: OptionalAndNullable<string>; sync: OptionalAndNullable<string>; }>; mutations: OptionalAndNullable<{ create: OptionalAndNullable<string>; update: OptionalAndNullable<string>; delete: OptionalAndNullable<string>; }>; subscriptions: OptionalAndNullable<{ onCreate: OptionalAndNullable<string>[]; onUpdate: OptionalAndNullable<string>[]; onDelete: OptionalAndNullable<string>[]; level: SubscriptionLevel; }>; timestamps: OptionalAndNullable<{ createdAt: OptionalAndNullable<string>; updatedAt: OptionalAndNullable<string>; }>; }; export const directiveDefinition = /* GraphQl */ ` directive @model( queries: ModelQueryMap mutations: ModelMutationMap subscriptions: ModelSubscriptionMap timestamps: TimestampConfiguration ) on OBJECT input ModelMutationMap { create: String update: String delete: String } input ModelQueryMap { get: String list: String } input ModelSubscriptionMap { onCreate: [String] onUpdate: [String] onDelete: [String] level: ModelSubscriptionLevel } enum ModelSubscriptionLevel { off public on } input TimestampConfiguration { createdAt: String updatedAt: String } `; type ModelTransformerOptions = { EnableDeletionProtection?: boolean; SyncConfig?: SyncConfig; }; export class ModelTransformer extends TransformerModelBase implements TransformerModelProvider { private options: ModelTransformerOptions; private datasourceMap: Record<string, DataSourceProvider> = {}; private ddbTableMap: Record<string, ITable> = {}; private resolverMap: Record<string, TransformerResolverProvider> = {}; private typesWithModelDirective: Set<string> = new Set(); /** * A Map to hold the directive configuration */ private modelDirectiveConfig: Map<string, ModelDirectiveConfiguration> = new Map(); constructor(options: ModelTransformerOptions = {}) { super('amplify-model-transformer', directiveDefinition); this.options = this.getOptions(options); } before = (ctx: TransformerBeforeStepContextProvider) => { // add model related-parameters to the root stack ctx.stackManager.addParameter(ResourceConstants.PARAMETERS.DynamoDBModelTableReadIOPS, { description: 'The number of read IOPS the table should support.', type: 'Number', default: 5, }); ctx.stackManager.addParameter(ResourceConstants.PARAMETERS.DynamoDBModelTableWriteIOPS, { description: 'The number of write IOPS the table should support.', type: 'Number', default: 5, }); ctx.stackManager.addParameter(ResourceConstants.PARAMETERS.DynamoDBBillingMode, { description: 'Configure @model types to create DynamoDB tables with PAY_PER_REQUEST or PROVISIONED billing modes.', default: 'PAY_PER_REQUEST', allowedValues: ['PAY_PER_REQUEST', 'PROVISIONED'], }); ctx.stackManager.addParameter(ResourceConstants.PARAMETERS.DynamoDBEnablePointInTimeRecovery, { description: 'Whether to enable Point in Time Recovery on the table.', type: 'String', default: 'false', allowedValues: ['true', 'false'], }); ctx.stackManager.addParameter(ResourceConstants.PARAMETERS.DynamoDBEnableServerSideEncryption, { description: 'Enable server side encryption powered by KMS.', type: 'String', default: 'true', allowedValues: ['true', 'false'], }); }; object = (definition: ObjectTypeDefinitionNode, directive: DirectiveNode, ctx: TransformerSchemaVisitStepContextProvider): void => { const isTypeNameReserved = definition.name.value === ctx.output.getQueryTypeName() || definition.name.value === ctx.output.getMutationTypeName() || definition.name.value === ctx.output.getSubscriptionTypeName(); if (isTypeNameReserved) { throw new InvalidDirectiveError( `'${definition.name.value}' is a reserved type name and currently in use within the default schema element.`, ); } // todo: get model configuration with default values and store it in the map const typeName = definition.name.value; if (ctx.isProjectUsingDataStore()) { SyncUtils.validateResolverConfigForType(ctx, typeName); } const directiveWrapped: DirectiveWrapper = new DirectiveWrapper(directive); const options = directiveWrapped.getArguments({ queries: { get: toCamelCase(['get', typeName]), list: toCamelCase(['list', plurality(typeName, true)]), ...(ctx.isProjectUsingDataStore() ? { sync: toCamelCase(['sync', plurality(typeName, true)]) } : undefined), }, mutations: { create: toCamelCase(['create', typeName]), update: toCamelCase(['update', typeName]), delete: toCamelCase(['delete', typeName]), }, subscriptions: { level: SubscriptionLevel.on, onCreate: [this.ensureValidSubscriptionName(toCamelCase(['onCreate', typeName]))], onDelete: [this.ensureValidSubscriptionName(toCamelCase(['onDelete', typeName]))], onUpdate: [this.ensureValidSubscriptionName(toCamelCase(['onUpdate', typeName]))], }, timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt', }, }); if (options.subscriptions?.onCreate && !Array.isArray(options.subscriptions.onCreate)) { options.subscriptions.onCreate = [options.subscriptions.onCreate]; } if (options.subscriptions?.onDelete && !Array.isArray(options.subscriptions.onDelete)) { options.subscriptions.onDelete = [options.subscriptions.onDelete]; } if (options.subscriptions?.onUpdate && !Array.isArray(options.subscriptions.onUpdate)) { options.subscriptions.onUpdate = [options.subscriptions.onUpdate]; } this.modelDirectiveConfig.set(typeName, options); this.typesWithModelDirective.add(typeName); }; validate = () => {}; prepare = (context: TransformerPrepareStepContextProvider) => { for (const modelTypeName of this.typesWithModelDirective) { const type = context.output.getObject(modelTypeName); context.providerRegistry.registerDataSourceProvider(type!, this); } }; transformSchema = (ctx: TransformerTransformSchemaStepContextProvider): void => { // add the model input conditions addModelConditionInputs(ctx); this.ensureModelSortDirectionEnum(ctx); for (const type of this.typesWithModelDirective) { const def = ctx.output.getObject(type)!; const hasAuth = def.directives!.some(dir => dir.name.value === 'auth'); // add Non Model type inputs this.createNonModelInputs(ctx, def); const queryFields = this.createQueryFields(ctx, def); ctx.output.addQueryFields(queryFields); const mutationFields = this.createMutationFields(ctx, def); ctx.output.addMutationFields(mutationFields); const subscriptionsFields = this.createSubscriptionFields(ctx, def!); ctx.output.addSubscriptionFields(subscriptionsFields); // Update the field with auto generatable Fields this.addAutoGeneratableFields(ctx, type); if (ctx.isProjectUsingDataStore()) { this.addModelSyncFields(ctx, type); } // global auth check if (!hasAuth && ctx.sandboxModeEnabled && ctx.authConfig.defaultAuthentication.authenticationType !== 'API_KEY') { const apiKeyDirArray = [makeDirective(API_KEY_DIRECTIVE, [])]; extendTypeWithDirectives(ctx, def.name.value, apiKeyDirArray); propagateApiKeyToNestedTypes(ctx as TransformerContextProvider, def, new Set<string>()); for (let operationField of queryFields) { const operationName = operationField.name.value; addDirectivesToOperation(ctx, ctx.output.getQueryTypeName()!, operationName, apiKeyDirArray); } for (let operationField of mutationFields) { const operationName = operationField.name.value; addDirectivesToOperation(ctx, ctx.output.getMutationTypeName()!, operationName, apiKeyDirArray); } for (let operationField of subscriptionsFields) { const operationName = operationField.name.value; addDirectivesToOperation(ctx, ctx.output.getSubscriptionTypeName()!, operationName, apiKeyDirArray); } } } }; generateResolvers = (context: TransformerContextProvider): void => { for (let type of this.typesWithModelDirective) { const def = context.output.getObject(type)!; // This name is used by the mock functionality. Changing this can break mock. const tableLogicalName = `${def!.name.value}Table`; const stack = context.stackManager.getStackFor(tableLogicalName, def!.name.value); this.createModelTable(stack, def!, context); const queryFields = this.getQueryFieldNames(context, def!); for (let query of queryFields.values()) { let resolver; switch (query.type) { case QueryFieldType.GET: resolver = this.generateGetResolver(context, def!, query.typeName, query.fieldName, query.resolverLogicalId); break; case QueryFieldType.LIST: resolver = this.generateListResolver(context, def!, query.typeName, query.fieldName, query.resolverLogicalId); break; case QueryFieldType.SYNC: resolver = this.generateSyncResolver(context, def!, query.typeName, query.fieldName, query.resolverLogicalId); break; default: throw new Error('Unknown query field type'); } // TODO: add mechanism to add an auth like rule to all non auth @models // this way we can just depend on auth to add the check resolver.addToSlot( 'postAuth', MappingTemplate.s3MappingTemplateFromString( generateAuthExpressionForSandboxMode(context.sandboxModeEnabled), `${query.typeName}.${query.fieldName}.{slotName}.{slotIndex}.req.vtl`, ), ); resolver.mapToStack(stack); context.resolvers.addResolver(query.typeName, query.fieldName, resolver); } const mutationFields = this.getMutationFieldNames(context, def!); for (let mutation of mutationFields.values()) { let resolver; switch (mutation.type) { case MutationFieldType.CREATE: resolver = this.generateCreateResolver(context, def!, mutation.typeName, mutation.fieldName, mutation.resolverLogicalId); break; case MutationFieldType.DELETE: resolver = this.generateDeleteResolver(context, def!, mutation.typeName, mutation.fieldName, mutation.resolverLogicalId); break; case MutationFieldType.UPDATE: resolver = this.generateUpdateResolver(context, def!, mutation.typeName, mutation.fieldName, mutation.resolverLogicalId); break; default: throw new Error('Unknown mutation field type'); } resolver.addToSlot( 'postAuth', MappingTemplate.s3MappingTemplateFromString( generateAuthExpressionForSandboxMode(context.sandboxModeEnabled), `${mutation.typeName}.${mutation.fieldName}.{slotName}.{slotIndex}.req.vtl`, ), ); resolver.mapToStack(stack); context.resolvers.addResolver(mutation.typeName, mutation.fieldName, resolver); } const subscriptionLevel = this.modelDirectiveConfig.get(def.name.value)?.subscriptions?.level; // in order to create subscription resolvers the level needs to be on if (subscriptionLevel === SubscriptionLevel.on) { const subscriptionFields = this.getSubscriptionFieldNames(context, def!); for (let subscription of subscriptionFields.values()) { let resolver; switch (subscription.type) { case SubscriptionFieldType.ON_CREATE: resolver = this.generateOnCreateResolver( context, def, subscription.typeName, subscription.fieldName, subscription.resolverLogicalId, ); break; case SubscriptionFieldType.ON_UPDATE: resolver = this.generateOnUpdateResolver( context, def, subscription.typeName, subscription.fieldName, subscription.resolverLogicalId, ); break; case SubscriptionFieldType.ON_DELETE: resolver = this.generateOnDeleteResolver( context, def, subscription.typeName, subscription.fieldName, subscription.resolverLogicalId, ); break; default: throw new Error('Unknown subscription field type'); } resolver.addToSlot( 'postAuth', MappingTemplate.s3MappingTemplateFromString( generateAuthExpressionForSandboxMode(context.sandboxModeEnabled), `${subscription.typeName}.${subscription.fieldName}.{slotName}.{slotIndex}.req.vtl`, ), ); resolver.mapToStack(stack); context.resolvers.addResolver(subscription.typeName, subscription.fieldName, resolver); } } } }; generateGetResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `Get${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateQueryResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString(generateGetRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString(generateGetResponseTemplate(isSyncEnabled), `${typeName}.${fieldName}.res.vtl`), ); } return this.resolverMap[resolverKey]; }; generateListResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `List${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateQueryResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString(generateListRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString( generateDefaultResponseMappingTemplate(isSyncEnabled), `${typeName}.${fieldName}.res.vtl`, ), ); } return this.resolverMap[resolverKey]; }; generateUpdateResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `Update${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { const resolver = ctx.resolvers.generateMutationResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString( generateUpdateRequestTemplate(typeName, isSyncEnabled), `${typeName}.${fieldName}.req.vtl`, ), MappingTemplate.s3MappingTemplateFromString( generateDefaultResponseMappingTemplate(isSyncEnabled, true), `${typeName}.${fieldName}.res.vtl`, ), ); // Todo: get the slot index from the resolver to keep the name unique and show the order of functions resolver.addToSlot( 'init', MappingTemplate.s3MappingTemplateFromString( generateUpdateInitSlotTemplate(type.name.value, this.modelDirectiveConfig.get(type.name.value)!), `${typeName}.${fieldName}.{slotName}.{slotIndex}.req.vtl`, ), ); this.resolverMap[resolverKey] = resolver; } return this.resolverMap[resolverKey]; }; generateDeleteResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `delete${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateMutationResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString(generateDeleteRequestTemplate(isSyncEnabled), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString( generateDefaultResponseMappingTemplate(isSyncEnabled, true), `${typeName}.${fieldName}.res.vtl`, ), ); } return this.resolverMap[resolverKey]; }; generateOnCreateResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const resolverKey = `OnCreate${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateSubscriptionResolver( typeName, fieldName, resolverLogicalId, MappingTemplate.s3MappingTemplateFromString(generateSubscriptionRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString(generateSubscriptionResponseTemplate(), `${typeName}.${fieldName}.res.vtl`), ); } return this.resolverMap[resolverKey]; }; generateOnUpdateResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const resolverKey = `OnUpdate${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateSubscriptionResolver( typeName, fieldName, resolverLogicalId, MappingTemplate.s3MappingTemplateFromString(generateSubscriptionRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString(generateSubscriptionResponseTemplate(), `${typeName}.${fieldName}.res.vtl`), ); } return this.resolverMap[resolverKey]; }; generateOnDeleteResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const resolverKey = `OnDelete${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateSubscriptionResolver( typeName, fieldName, resolverLogicalId, MappingTemplate.s3MappingTemplateFromString(generateSubscriptionRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString(generateSubscriptionResponseTemplate(), `${typeName}.${fieldName}.res.vtl`), ); } return this.resolverMap[resolverKey]; }; generateSyncResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `Sync${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { this.resolverMap[resolverKey] = ctx.resolvers.generateQueryResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString(generateSyncRequestTemplate(), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString( generateDefaultResponseMappingTemplate(isSyncEnabled), `${typeName}.${fieldName}.res.vtl`, ), ); } return this.resolverMap[resolverKey]; }; getQueryFieldNames = ( ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode, ): Set<{ fieldName: string; typeName: string; type: QueryFieldType; resolverLogicalId: string }> => { const typeName = type.name.value; const fields: Set<{ fieldName: string; typeName: string; type: QueryFieldType; resolverLogicalId: string }> = new Set(); const modelDirectiveConfig = this.modelDirectiveConfig.get(type.name.value); if (modelDirectiveConfig?.queries?.get) { fields.add({ typeName: 'Query', fieldName: modelDirectiveConfig.queries.get || toCamelCase(['get', typeName]), type: QueryFieldType.GET, resolverLogicalId: ResolverResourceIDs.DynamoDBGetResolverResourceID(typeName), }); } if (modelDirectiveConfig?.queries?.list) { fields.add({ typeName: 'Query', fieldName: modelDirectiveConfig.queries.list || toCamelCase(['list', typeName]), type: QueryFieldType.LIST, resolverLogicalId: ResolverResourceIDs.DynamoDBListResolverResourceID(typeName), }); } if (modelDirectiveConfig?.queries?.sync) { fields.add({ typeName: 'Query', fieldName: modelDirectiveConfig.queries.sync || toCamelCase(['sync', typeName]), type: QueryFieldType.SYNC, resolverLogicalId: ResolverResourceIDs.SyncResolverResourceID(typeName), }); } return fields; }; getMutationFieldNames = ( ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode, ): Set<{ fieldName: string; typeName: string; type: MutationFieldType; resolverLogicalId: string }> => { // Todo: get fields names from the directives const typeName = type.name.value; const modelDirectiveConfig = this.modelDirectiveConfig.get(typeName); const getMutationType = (type: string): MutationFieldType => { switch (type) { case 'create': return MutationFieldType.CREATE; case 'update': return MutationFieldType.UPDATE; case 'delete': return MutationFieldType.DELETE; default: throw new Error('Unknown mutation type'); } }; const getMutationResolverLogicalId = (type: string): string => { switch (type) { case 'create': return ResolverResourceIDs.DynamoDBCreateResolverResourceID(typeName); case 'update': return ResolverResourceIDs.DynamoDBUpdateResolverResourceID(typeName); case 'delete': return ResolverResourceIDs.DynamoDBDeleteResolverResourceID(typeName); default: throw new Error('Unknown mutation type'); } }; const fieldNames: Set<{ fieldName: string; typeName: string; type: MutationFieldType; resolverLogicalId: string }> = new Set(); for (let [mutationType, mutationName] of Object.entries(modelDirectiveConfig?.mutations || {})) { if (mutationName) { fieldNames.add({ typeName: 'Mutation', fieldName: mutationName, type: getMutationType(mutationType), resolverLogicalId: getMutationResolverLogicalId(mutationType), }); } } return fieldNames; }; getMutationName = ( subscriptionType: SubscriptionFieldType, mutationMap: Set<{ fieldName: string; typeName: string; type: MutationFieldType; resolverLogicalId: string; }>, ): string => { const mutationToSubscriptionTypeMap = { [SubscriptionFieldType.ON_CREATE]: MutationFieldType.CREATE, [SubscriptionFieldType.ON_UPDATE]: MutationFieldType.UPDATE, [SubscriptionFieldType.ON_DELETE]: MutationFieldType.DELETE, }; const mutation = Array.from(mutationMap).find(m => m.type == mutationToSubscriptionTypeMap[subscriptionType]); if (mutation) { return mutation.fieldName; } throw new Error('Unknown Subscription type'); }; private createQueryFields = (ctx: TransformerValidationStepContextProvider, def: ObjectTypeDefinitionNode): FieldDefinitionNode[] => { const queryFields: FieldDefinitionNode[] = []; const queryFieldNames = this.getQueryFieldNames(ctx, def!); for (const queryField of queryFieldNames.values()) { const outputType = this.getOutputType(ctx, def, queryField); const args = this.getInputs(ctx, def!, { fieldName: queryField.fieldName, typeName: queryField.typeName, type: queryField.type, }); queryFields.push(makeField(queryField.fieldName, args, makeNamedType(outputType.name.value))); } return queryFields; }; private createMutationFields = (ctx: TransformerValidationStepContextProvider, def: ObjectTypeDefinitionNode): FieldDefinitionNode[] => { const mutationFields: FieldDefinitionNode[] = []; const mutationFieldNames = this.getMutationFieldNames(ctx, def!); for (const mutationField of mutationFieldNames) { const args = this.getInputs(ctx, def!, { fieldName: mutationField.fieldName, typeName: mutationField.typeName, type: mutationField.type, }); mutationFields.push(makeField(mutationField.fieldName, args, makeNamedType(def!.name.value))); } return mutationFields; }; private createSubscriptionFields = ( ctx: TransformerTransformSchemaStepContextProvider, def: ObjectTypeDefinitionNode, ): FieldDefinitionNode[] => { const subscriptionToMutationsMap = this.getSubscriptionToMutationsReverseMap(ctx, def); const mutationFields = this.getMutationFieldNames(ctx, def!); const subscriptionFields: FieldDefinitionNode[] = []; for (const subscriptionFieldName of Object.keys(subscriptionToMutationsMap)) { const maps = subscriptionToMutationsMap[subscriptionFieldName]; const args: InputValueDefinitionNode[] = []; maps.map(it => args.concat( this.getInputs(ctx, def!, { fieldName: it.fieldName, typeName: it.typeName, type: it.type, }), ), ); const mutationNames = maps.map(it => this.getMutationName(it.type, mutationFields)); // Todo use directive wrapper to build the directive node const directive = makeDirective('aws_subscribe', [makeArgument('mutations', makeValueNode(mutationNames))]); const field = makeField(subscriptionFieldName, args, makeNamedType(def!.name.value), [directive]); subscriptionFields.push(field); } return subscriptionFields; }; getSubscriptionFieldNames = ( ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode, ): Set<{ fieldName: string; typeName: string; type: SubscriptionFieldType; resolverLogicalId: string; }> => { const fields: Set<{ fieldName: string; typeName: string; type: SubscriptionFieldType; resolverLogicalId: string; }> = new Set(); const modelDirectiveConfig = this.modelDirectiveConfig.get(type.name.value); if (modelDirectiveConfig?.subscriptions?.level !== SubscriptionLevel.off) { if (modelDirectiveConfig?.subscriptions?.onCreate && modelDirectiveConfig.mutations?.create) { for (const fieldName of modelDirectiveConfig.subscriptions.onCreate) { fields.add({ typeName: 'Subscription', fieldName: fieldName, type: SubscriptionFieldType.ON_CREATE, resolverLogicalId: ResolverResourceIDs.ResolverResourceID('Subscription', fieldName), }); } } if (modelDirectiveConfig?.subscriptions?.onUpdate && modelDirectiveConfig.mutations?.update) { for (const fieldName of modelDirectiveConfig.subscriptions.onUpdate) { fields.add({ typeName: 'Subscription', fieldName: fieldName, type: SubscriptionFieldType.ON_UPDATE, resolverLogicalId: ResolverResourceIDs.ResolverResourceID('Subscription', fieldName), }); } } if (modelDirectiveConfig?.subscriptions?.onDelete && modelDirectiveConfig.mutations?.delete) { for (const fieldName of modelDirectiveConfig.subscriptions.onDelete) { fields.add({ typeName: 'Subscription', fieldName: fieldName, type: SubscriptionFieldType.ON_DELETE, resolverLogicalId: ResolverResourceIDs.ResolverResourceID('Subscription', fieldName), }); } } } return fields; }; getDataSourceResource = (ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode): DataSourceInstance => { // Todo: add sanity check to ensure the type has an table return this.ddbTableMap[type.name.value]; }; getDataSourceType = (): AppSyncDataSourceType => { return AppSyncDataSourceType.AMAZON_DYNAMODB; }; generateCreateResolver = ( ctx: TransformerContextProvider, type: ObjectTypeDefinitionNode, typeName: string, fieldName: string, resolverLogicalId: string, ): TransformerResolverProvider => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const dataSource = this.datasourceMap[type.name.value]; const resolverKey = `Create${generateResolverKey(typeName, fieldName)}`; if (!this.resolverMap[resolverKey]) { const resolver = ctx.resolvers.generateMutationResolver( typeName, fieldName, resolverLogicalId, dataSource, MappingTemplate.s3MappingTemplateFromString(generateCreateRequestTemplate(type.name.value), `${typeName}.${fieldName}.req.vtl`), MappingTemplate.s3MappingTemplateFromString( generateDefaultResponseMappingTemplate(isSyncEnabled, true), `${typeName}.${fieldName}.res.vtl`, ), ); this.resolverMap[resolverKey] = resolver; resolver.addToSlot( 'init', MappingTemplate.s3MappingTemplateFromString( generateCreateInitSlotTemplate(type.name.value, this.modelDirectiveConfig.get(type.name.value)!), `${typeName}.${fieldName}.{slotName}.{slotIndex}.req.vtl`, ), ); } return this.resolverMap[resolverKey]; }; getInputs = ( ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode, operation: { fieldName: string; typeName: string; type: QueryFieldType | MutationFieldType | SubscriptionFieldType; }, ): InputValueDefinitionNode[] => { const isSyncEnabled = ctx.isProjectUsingDataStore(); const knownModels = this.typesWithModelDirective; let conditionInput: InputObjectTypeDefinitionNode; if ([MutationFieldType.CREATE, MutationFieldType.DELETE, MutationFieldType.UPDATE].includes(operation.type as MutationFieldType)) { const conditionTypeName = toPascalCase(['Model', type.name.value, 'ConditionInput']); const filterInputs = createEnumModelFilters(ctx, type); conditionInput = makeMutationConditionInput(ctx, conditionTypeName, type); filterInputs.push(conditionInput); for (let input of filterInputs) { const conditionInputName = input.name.value; if (!ctx.output.getType(conditionInputName)) { ctx.output.addInput(input); } } } switch (operation.type) { case QueryFieldType.GET: return [makeInputValueDefinition('id', makeNonNullType(makeNamedType('ID')))]; case QueryFieldType.LIST: const filterInputName = toPascalCase(['Model', type.name.value, 'FilterInput']); const filterInputs = createEnumModelFilters(ctx, type); filterInputs.push(makeListQueryFilterInput(ctx, filterInputName, type)); for (let input of filterInputs) { const conditionInputName = input.name.value; if (!ctx.output.getType(conditionInputName)) { ctx.output.addInput(input); } } return [ makeInputValueDefinition('filter', makeNamedType(filterInputName)), makeInputValueDefinition('limit', makeNamedType('Int')), makeInputValueDefinition('nextToken', makeNamedType('String')), ]; case QueryFieldType.SYNC: const syncFilterInputName = toPascalCase(['Model', type.name.value, 'FilterInput']); const syncFilterInputs = makeListQueryFilterInput(ctx, syncFilterInputName, type); const conditionInputName = syncFilterInputs.name.value; if (!ctx.output.getType(conditionInputName)) { ctx.output.addInput(syncFilterInputs); } return [ makeInputValueDefinition('filter', makeNamedType(syncFilterInputName)), makeInputValueDefinition('limit', makeNamedType('Int')), makeInputValueDefinition('nextToken', makeNamedType('String')), makeInputValueDefinition('lastSync', makeNamedType('AWSTimestamp')), ]; case MutationFieldType.CREATE: const createInputField = makeCreateInputField( type, this.modelDirectiveConfig.get(type.name.value)!, knownModels, ctx.inputDocument, isSyncEnabled, ); const createInputTypeName = createInputField.name.value; if (!ctx.output.getType(createInputField.name.value)) { ctx.output.addInput(createInputField); } return [ makeInputValueDefinition('input', makeNonNullType(makeNamedType(createInputTypeName))), makeInputValueDefinition('condition', makeNamedType(conditionInput!.name.value)), ]; case MutationFieldType.DELETE: const deleteInputField = makeDeleteInputField(type, isSyncEnabled); const deleteInputTypeName = deleteInputField.name.value; if (!ctx.output.getType(deleteInputField.name.value)) { ctx.output.addInput(deleteInputField); } return [ makeInputValueDefinition('input', makeNonNullType(makeNamedType(deleteInputTypeName))), makeInputValueDefinition('condition', makeNamedType(conditionInput!.name.value)), ]; case MutationFieldType.UPDATE: const updateInputField = makeUpdateInputField( type, this.modelDirectiveConfig.get(type.name.value)!, knownModels, ctx.inputDocument, isSyncEnabled, ); const updateInputTypeName = updateInputField.name.value; if (!ctx.output.getType(updateInputField.name.value)) { ctx.output.addInput(updateInputField); } return [ makeInputValueDefinition('input', makeNonNullType(makeNamedType(updateInputTypeName))), makeInputValueDefinition('condition', makeNamedType(conditionInput!.name.value)), ]; case SubscriptionFieldType.ON_CREATE: case SubscriptionFieldType.ON_DELETE: case SubscriptionFieldType.ON_UPDATE: return []; break; default: throw new Error('Unknown operation type'); } return []; }; getOutputType = ( ctx: TransformerTransformSchemaStepContextProvider, type: ObjectTypeDefinitionNode, operation: { fieldName: string; typeName: string; type: QueryFieldType | MutationFieldType | SubscriptionFieldType; }, ): ObjectTypeDefinitionNode => { let outputType: ObjectTypeDefinitionNode; switch (operation.type) { case MutationFieldType.CREATE: case MutationFieldType.UPDATE: case MutationFieldType.DELETE: case QueryFieldType.GET: case SubscriptionFieldType.ON_CREATE: case SubscriptionFieldType.ON_DELETE: case SubscriptionFieldType.ON_UPDATE: outputType = type; break; case QueryFieldType.SYNC: case QueryFieldType.LIST: const isSyncEnabled = ctx.isProjectUsingDataStore(); const connectionFieldName = toPascalCase(['Model', type.name.value, 'Connection']); outputType = makeListQueryModel(type, connectionFieldName, isSyncEnabled); break; default: throw new Error(`${operation.type} not supported for ${type.name.value}`); } if (!ctx.output.getObject(outputType.name.value)) { ctx.output.addObject(outputType); } return outputType; }; private createNonModelInputs = (ctx: TransformerTransformSchemaStepContextProvider, obj: ObjectTypeDefinitionNode): void => { for (let field of obj.fields || []) { if (!isScalar(field.type)) { const def = ctx.output.getType(getBaseType(field.type)); if (def && def.kind == 'ObjectTypeDefinition' && !this.isModelField(def.name.value)) { const name = this.getNonModelInputObjectName(def.name.value); if (!ctx.output.getType(name)) { const inputObj = InputObjectDefinitionWrapper.fromObject(name, def, ctx.inputDocument); ctx.output.addInput(inputObj.serialize()); this.createNonModelInputs(ctx, def); } } } } }; private isModelField = (name: string): boolean => { return this.typesWithModelDirective.has(name) ? true : false; }; private getNonModelInputObjectName = (name: string): string => { return `${name}Input`; }; /** * Model directive automatically adds id, created and updated time stamps to the filed, if they are configured * @param name Name of the type */ private addAutoGeneratableFields = (ctx: TransformerTransformSchemaStepContextProvider, name: string): void => { const modelDirectiveConfig = this.modelDirectiveConfig.get(name); const typeObj = ctx.output.getObject(name); if (!typeObj) { throw new Error(`Type ${name} is missing in outputs`); } const typeWrapper = new ObjectDefinitionWrapper(typeObj); if (!typeWrapper.hasField('id')) { const idField = FieldWrapper.create('id', 'ID'); typeWrapper.addField(idField); } const timestamps = []; if (modelDirectiveConfig?.timestamps) { if (modelDirectiveConfig.timestamps.createdAt !== null) { timestamps.push(modelDirectiveConfig.timestamps.createdAt ?? 'createdAt'); } if (modelDirectiveConfig.timestamps.updatedAt !== null) { timestamps.push(modelDirectiveConfig.timestamps.updatedAt ?? 'updatedAt'); } } for (let fieldName of timestamps) { if (typeWrapper.hasField(fieldName)) { const field = typeWrapper.getField(fieldName); if (!['String', 'AWSDateTime'].includes(field.getTypeName())) { console.warn(`type ${name}.${fieldName} is not of String or AWSDateTime. Auto population is not supported`); } } else { const field = FieldWrapper.create(fieldName, 'AWSDateTime'); typeWrapper.addField(field); } } ctx.output.updateObject(typeWrapper.serialize()); }; private addModelSyncFields = (ctx: TransformerTransformSchemaStepContextProvider, name: string): void => { const typeObj = ctx.output.getObject(name); if (!typeObj) { throw new Error(`Type ${name} is missing in outputs`); } const typeWrapper = new ObjectDefinitionWrapper(typeObj); typeWrapper.addField(FieldWrapper.create('_version', 'Int')); typeWrapper.addField(FieldWrapper.create('_deleted', 'Boolean', true)); typeWrapper.addField(FieldWrapper.create('_lastChangedAt', 'AWSTimestamp')); ctx.output.updateObject(typeWrapper.serialize()); }; private getSubscriptionToMutationsReverseMap = ( ctx: TransformerValidationStepContextProvider, def: ObjectTypeDefinitionNode, ): { [subField: string]: { fieldName: string; typeName: string; type: SubscriptionFieldType }[] } => { const subscriptionToMutationsMap: { [subField: string]: { fieldName: string; typeName: string; type: SubscriptionFieldType }[] } = {}; const subscriptionFieldNames = this.getSubscriptionFieldNames(ctx, def); for (const subscriptionFieldName of subscriptionFieldNames) { if (!subscriptionToMutationsMap[subscriptionFieldName.fieldName]) { subscriptionToMutationsMap[subscriptionFieldName.fieldName] = []; } subscriptionToMutationsMap[subscriptionFieldName.fieldName].push(subscriptionFieldName); } return subscriptionToMutationsMap; }; private createModelTable(stack: cdk.Stack, def: ObjectTypeDefinitionNode, context: TransformerContextProvider) { const tableLogicalName = `${def!.name.value}Table`; const tableName = context.resourceHelper.generateResourceName(def!.name.value); // Add parameters. const env = context.stackManager.getParameter(ResourceConstants.PARAMETERS.Env) as cdk.CfnParameter; const readIops = new cdk.CfnParameter(stack, ResourceConstants.PARAMETERS.DynamoDBModelTableReadIOPS, { description: 'The number of read IOPS the table should support.', type: 'Number', default: 5, }); const writeIops = new cdk.CfnParameter(stack, ResourceConstants.PARAMETERS.DynamoDBModelTableWriteIOPS, { description: 'The number of write IOPS the table should support.', type: 'Number', default: 5, }); const billingMode = new cdk.CfnParameter(stack, ResourceConstants.PARAMETERS.DynamoDBBillingMode, { description: 'Configure @model types to create DynamoDB tables with PAY_PER_REQUEST or PROVISIONED billing modes.', type: 'String', default: 'PAY_PER_REQUEST', allowedValues: ['PAY_PER_REQUEST', 'PROVISIONED'], }); const pointInTimeRecovery = new cdk.CfnParameter(stack, ResourceConstants.PARAMETERS.DynamoDBEnablePointInTimeRecovery, { description: 'Whether to enable Point in Time Recovery on the table.', type: 'String', default: 'false', allowedValues: ['true', 'false'], }); const enableSSE = new cdk.CfnParameter(stack, ResourceConstants.PARAMETERS.DynamoDBEnableServerSideEncryption, { description: 'Enable server side encryption powered by KMS.', type: 'String', default: 'true', allowedValues: ['true', 'false'], }); // add the connection between the root and nested stack so the values can be passed down (stack as TransformerNestedStack).setParameter(readIops.node.id, cdk.Fn.ref(ResourceConstants.PARAMETERS.DynamoDBModelTableReadIOPS)); (stack as TransformerNestedStack).setParameter(writeIops.node.id, cdk.Fn.ref(ResourceConstants.PARAMETERS.DynamoDBModelTableWriteIOPS)); (stack as TransformerNestedStack).setParameter(billingMode.node.id, cdk.Fn.ref(ResourceConstants.PARAMETERS.DynamoDBBillingMode)); (stack as TransformerNestedStack).setParameter( pointInTimeRecovery.node.id, cdk.Fn.ref(ResourceConstants.PARAMETERS.DynamoDBEnablePointInTimeRecovery), ); (stack as TransformerNestedStack).setParameter( enableSSE.node.id, cdk.Fn.ref(ResourceConstants.PARAMETERS.DynamoDBEnableServerSideEncryption), ); // Add conditions. // eslint-disable-next-line no-new new cdk.CfnCondition(stack, ResourceConstants.CONDITIONS.HasEnvironmentParameter, { expression: cdk.Fn.conditionNot(cdk.Fn.conditionEquals(env, ResourceConstants.NONE)), }); const useSSE = new cdk.CfnCondition(stack, ResourceConstants.CONDITIONS.ShouldUseServerSideEncryption, { expression: cdk.Fn.conditionEquals(enableSSE, 'true'), }); const usePayPerRequestBilling = new cdk.CfnCondition(stack, ResourceConstants.CONDITIONS.ShouldUsePayPerRequestBilling, { expression: cdk.Fn.conditionEquals(billingMode, 'PAY_PER_REQUEST'), }); const usePointInTimeRecovery = new cdk.CfnCondition(stack, ResourceConstants.CONDITIONS.ShouldUsePointInTimeRecovery, { expression: cdk.Fn.conditionEquals(pointInTimeRecovery, 'true'), }); const removalPolicy = this.options.EnableDeletionProtection ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY; // Expose a way in context to allow proper resource naming const table = new Table(stack, tableLogicalName, { tableName, partitionKey: { name: 'id', type: AttributeType.STRING, }, stream: StreamViewType.NEW_AND_OLD_IMAGES, encryption: TableEncryption.DEFAULT, removalPolicy: removalPolicy, ...(context.isProjectUsingDataStore() ? { timeToLiveAttribute: '_ttl' } : undefined), }); const cfnTable = table.node.defaultChild as CfnTable; cfnTable.provisionedThroughput = cdk.Fn.conditionIf(usePayPerRequestBilling.logicalId, cdk.Fn.ref('AWS::NoValue'), { ReadCapacityUnits: readIops, WriteCapacityUnits: writeIops, }); cfnTable.pointInTimeRecoverySpecification = cdk.Fn.conditionIf( usePointInTimeRecovery.logicalId, { PointInTimeRecoveryEnabled: true }, cdk.Fn.ref('AWS::NoValue'), ); cfnTable.billingMode = cdk.Fn.conditionIf(usePayPerRequestBilling.logicalId, 'PAY_PER_REQUEST', cdk.Fn.ref('AWS::NoValue')).toString(); cfnTable.sseSpecification = { sseEnabled: cdk.Fn.conditionIf(useSSE.logicalId, true, false), }; const streamArnOutputId = `GetAtt${ModelResourceIDs.ModelTableStreamArn(def!.name.value)}`; // eslint-disable-next-line no-new new cdk.CfnOutput(stack, streamArnOutputId, { value: cdk.Fn.getAtt(tableLogicalName, 'StreamArn').toString(), description: 'Your DynamoDB table StreamArn.', exportName: cdk.Fn.join(':', [context.api.apiId, 'GetAtt', tableLogicalName, 'StreamArn']), }); const tableNameOutputId = `GetAtt${tableLogicalName}Name`; // eslint-disable-next-line no-new new cdk.CfnOutput(stack, tableNameOutputId, { value: cdk.Fn.ref(tableLogicalName), description: 'Your DynamoDB table name.', exportName: cdk.Fn.join(':', [context.api.apiId, 'GetAtt', tableLogicalName, 'Name']), }); const role = this.createIAMRole(context, def, stack, tableName); this.createModelTableDataSource(def, context, table, stack, role); } private createModelTableDataSource( def: ObjectTypeDefinitionNode, context: TransformerContextProvider, table: Table, stack: cdk.Stack, role: iam.Role, ) { const tableLogicalName = `${def!.name.value}Table`; const datasourceRoleLogicalID = ModelResourceIDs.ModelTableDataSourceID(def!.name.value); const dataSource = context.api.host.addDynamoDbDataSource( datasourceRoleLogicalID, table, { name: tableLogicalName, serviceRole: role }, stack, ); const cfnDataSource = dataSource.node.defaultChild as CfnDataSource; cfnDataSource.addDependsOn(role.node.defaultChild as CfnRole); if (context.isProjectUsingDataStore()) { const datasourceDynamoDb = cfnDataSource.dynamoDbConfig as any; datasourceDynamoDb.deltaSyncConfig = { deltaSyncTableName: context.resourceHelper.generateResourceName(SyncResourceIDs.syncTableName), deltaSyncTableTtl: '30', baseTableTtl: '43200', }; datasourceDynamoDb.versioned = true; } const datasourceOutputId = `GetAtt${datasourceRoleLogicalID}Name`; // eslint-disable-next-line no-new new cdk.CfnOutput(stack, datasourceOutputId, { value: dataSource.ds.attrName, description: 'Your model DataSource name.', exportName: cdk.Fn.join(':', [context.api.apiId, 'GetAtt', datasourceRoleLogicalID, 'Name']), }); // add the data source context.dataSources.add(def!, dataSource); this.datasourceMap[def!.name.value] = dataSource; } private createIAMRole(context: TransformerContextProvider, def: ObjectTypeDefinitionNode, stack: cdk.Stack, tableName: string) { const roleName = context.resourceHelper.generateIAMRoleName(ModelResourceIDs.ModelTableIAMRoleID(def!.name.value)); const role = new iam.Role(stack, ModelResourceIDs.ModelTableIAMRoleID(def!.name.value), { roleName: roleName, assumedBy: new iam.ServicePrincipal('appsync.amazonaws.com'), }); const amplifyDataStoreTableName = context.resourceHelper.generateResourceName(SyncResourceIDs.syncTableName); role.attachInlinePolicy( new iam.Policy(stack, 'DynamoDBAccess', { statements: [ new iam.PolicyStatement({ effect: iam.Effect.ALLOW, actions: [ 'dynamodb:BatchGetItem', 'dynamodb:BatchWriteItem', 'dynamodb:PutItem', 'dynamodb:DeleteItem', 'dynamodb:GetItem', 'dynamodb:Scan', 'dynamodb:Query', 'dynamodb:UpdateItem', ], resources: [ // eslint-disable-next-line no-template-curly-in-string cdk.Fn.sub('arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}', { tablename: tableName, }), // eslint-disable-next-line no-template-curly-in-string cdk.Fn.sub('arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}/*', { tablename: tableName, }), ...(context.isProjectUsingDataStore() ? [ // eslint-disable-next-line no-template-curly-in-string cdk.Fn.sub('arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}', { tablename: amplifyDataStoreTableName, }), // eslint-disable-next-line no-template-curly-in-string cdk.Fn.sub('arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tablename}/*', { tablename: amplifyDataStoreTableName, }), ] : []), ], }), ], }), ); const syncConfig = SyncUtils.getSyncConfig(context, def!.name.value); if (syncConfig && SyncUtils.isLambdaSyncConfig(syncConfig)) { role.attachInlinePolicy( SyncUtils.createSyncLambdaIAMPolicy(stack, syncConfig.LambdaConflictHandler.name, syncConfig.LambdaConflictHandler.region), ); } return role; } private ensureModelSortDirectionEnum(ctx: TransformerValidationStepContextProvider): void { if (!ctx.output.hasType('ModelSortDirection')) { const modelSortDirection = makeModelSortDirectionEnumObject(); ctx.output.addEnum(modelSortDirection); } } private getOptions = (options: ModelTransformerOptions): ModelTransformerOptions => { return { EnableDeletionProtection: false, ...options, }; }; private ensureValidSubscriptionName = (name: string): string => { if (name.length <= 50) return name; return name.slice(0, 45) + md5(name).slice(0, 5); }; }
the_stack
import { CompletionItemKind, Range, workspace as Workspace } from "vscode"; import { existsSync, readFileSync } from "fs"; import { resolve, dirname } from "path"; import { URI } from "vscode-uri"; import { ItemsRepository } from "../Backend/spItemsRepository"; import { FileItems } from "../Backend/spFilesRepository"; import { SPItem } from "../Backend/Items/spItems"; import { CommentItem } from "../Backend/Items/spCommentItem"; import { State } from "./stateEnum"; import { readDefine } from "./readDefine"; import { readMacro } from "./readMacro"; import { readInclude } from "./readInclude"; import { readEnum } from "./readEnum"; import { readLoopVariable } from "./readLoopVariable"; import { readVariable } from "./readVariable"; import { readProperty } from "./readProperty"; import { readTypeDef } from "./readTypeDef"; import { readTypeSet } from "./readTypeSet"; import { readFunction } from "./readFunction"; import { consumeComment } from "./consumeComment"; import { searchForDefinesInString } from "./searchForDefinesInString"; import { readMethodMap } from "./readMethodMap"; import { manageState } from "./manageState"; import { purgeCalls, positiveRange, parentCounter } from "./utils"; export function parseFile( file: string, completions: FileItems, itemsRepository: ItemsRepository, IsBuiltIn: boolean = false ) { if (!existsSync(file)) { return; } let data = readFileSync(file, "utf-8"); // Test for symbolic links let match = data.match(/^(?:\.\.\/)+(?:[\/\w\-])+\.\w+/); if (match !== null) { let folderpath = dirname(file); file = resolve(folderpath, match[0]); data = readFileSync(file, "utf-8"); } parseText(data, file, completions, itemsRepository, IsBuiltIn); } export function parseText( data: string, file: string, completions: FileItems, itemsRepository: ItemsRepository, IsBuiltIn: boolean = false ) { if (data === undefined) { return; // Asked to parse empty file } let lines = data.split("\n"); let parser = new Parser(lines, file, IsBuiltIn, completions, itemsRepository); parser.parse(); } export class Parser { completions: FileItems; state: State[]; scratch: any; state_data: any; lines: string[]; lineNb: number; file: string; IsBuiltIn: boolean; documents: Set<string>; lastFuncLine: number; lastFuncName: string; definesMap: Map<string, string>; enumMemberMap: Map<string, string>; macroArr: string[]; itemsRepository: ItemsRepository; debugging: boolean; anonymousEnumCount: number; constructor( lines: string[], file: string, IsBuiltIn: boolean, completions: FileItems, itemsRepository: ItemsRepository ) { this.completions = completions; this.state = [State.None]; this.lineNb = 0; this.lines = lines; this.file = file; this.IsBuiltIn = IsBuiltIn; this.documents = itemsRepository.documents; this.lastFuncLine = 0; this.lastFuncName = ""; // Get all the items from the itemsRepository for this file let items = itemsRepository.getAllItems(URI.file(this.file)); this.definesMap = this.getAllMembers(items, CompletionItemKind.Constant); this.enumMemberMap = this.getAllMembers( items, CompletionItemKind.EnumMember ); this.macroArr = this.getAllMacros(items); this.itemsRepository = itemsRepository; let debugSetting = Workspace.getConfiguration("sourcepawn").get( "trace.server" ); this.debugging = debugSetting == "messages" || debugSetting == "verbose"; this.anonymousEnumCount = 0; } parse() { let line: string; line = this.lines.shift(); while (line !== undefined) { searchForDefinesInString(this, line); this.interpLine(line); line = this.lines.shift(); this.lineNb++; } } interpLine(line: string) { // EOF if (line === undefined) return; // Match trailing single line comments let match = line.match(/^\s*[^\/\/\s]+(\/\/.+)$/); if (match) { let lineNb = this.lineNb < 1 ? 0 : this.lineNb; let start: number = line.search(/\/\//); let range = new Range(lineNb, start, lineNb, line.length); this.completions.set( `comment${lineNb}--${Math.random()}`, new CommentItem(this.file, range) ); } // Match trailing block comments match = line.match(/^\s*[^\/\*\s]+(\/\*.+)\*\//); if (match) { let lineNb = this.lineNb < 1 ? 0 : this.lineNb; let start: number = line.search(/\/\*/); let end: number = line.search(/\*\//); let range = new Range(lineNb, start, lineNb, end); this.completions.set( `comment${lineNb}--${Math.random()}`, new CommentItem(this.file, range) ); } // Match define match = line.match(/^\s*#define\s+(\w+)\s+([^]+)/); if (match) { readDefine(this, match, line); return; } match = line.match(/^\s*#define\s+(\w+)\s*\(([^\)]*)\)/); if (match) { readMacro(this, match, line); return; } // Match global include match = line.match(/^\s*#include\s+<([A-Za-z0-9\-_\/.]+)>/); if (match) { readInclude(this, match); return; } // Match relative include match = line.match(/^\s*#include\s+"([A-Za-z0-9\-_\/.]+)"/); if (match) { readInclude(this, match); return; } // Match enum structs match = line.match(/^\s*(?:enum\s+struct\s+)(\w*)\s*[^\{]*/); if (match) { readEnum(this, match, line, true); return; } // Match enums match = line.match(/^\s*enum(?:\s+(\w+))?\s*[^\{]*/); if (match && !/;\s*$/.test(line)) { readEnum(this, match, line, false); return; } // Match for loop iteration variable only in the current file match = line.match(/^\s*(?:for\s*\(\s*int\s+)([A-Za-z0-9_]*)/); if (match) { readLoopVariable(this, match, line); return; } match = line.match(/^\s*typedef\s+(\w+)\s*\=\s*function\s+(\w+).*/); if (match) { readTypeDef(this, match, line); return; } match = line.match(/^\s*typeset\s+(\w+)/); if (match) { readTypeSet(this, match, line); return; } // Match variables only in the current file match = line.match( /^\s*(?:(?:new|static|const|decl|public|stock)\s+)*\w+(?:\[\])?\s+(\w+\s*(?:\[[A-Za-z0-9 +\-\*_]*\])*\s*(?:=\s*[^;,]+)?(?:,|;))/ ); if (match && !this.IsBuiltIn) { readVariable(this, match, line); return; } match = line.match(/^\s*\/\*/); if (match) { consumeComment(this, line, false); return; } match = line.match(/^\s*\/\//); if (match) { consumeComment(this, line, true); return; } match = line.match( /^\s*methodmap\s+([a-zA-Z][a-zA-Z0-9_]*)(?:\s*<\s*([a-zA-Z][a-zA-Z0-9_]*))?/ ); if (match) { readMethodMap(this, match, line); return; } // Match properties match = line.match(/^\s*property\s+([a-zA-Z]\w*)\s+([a-zA-Z]\w*)/); if (match) { if (this.state.includes(State.Methodmap)) { this.state.push(State.Property); } try { readProperty(this, match, line); } catch (e) { console.error(e); if (this.debugging) { console.error(`At line ${this.lineNb} of ${this.file}`); } } return; } match = line.match( /^\s*(\bwhile\b|\belse\b|\bif\b|\bswitch\b|\bcase\b|\bdo\b)/ ); if (match) { // Check if we are still in the conditionnal of the control statement // for example, an if statement's conditionnal can span over several lines // and call functions let parenthesisNB = parentCounter(line); let lineCounter = 0; let iter = 0; while (parenthesisNB !== 0 && iter < 100) { iter++; line = this.lines[lineCounter]; lineCounter++; parenthesisNB += parentCounter(line); } // Now we test if the statement uses brackets, as short code blocks are usually // implemented without them. if (!/\{\s*$/.test(line)) { // Test the next line if we didn't match if (!/^\s*\{/.test(this.lines[lineCounter])) { return; } } this.state.push(State.Loop); return; } match = line.match( /^\s*(?:(?:static|native|stock|public|forward)\s+)*(?:[a-zA-Z\-_0-9]:)?([^\s]+)\s*(\w*)\s*\(([^\)]*(?:\)?))(?:\s*)(?:\{?)(?:\s*)(?:[^\;\s]*);?\s*$/ ); if (match) { readFunction(this, match, line); } match = line.match(/^\s*}/); if (match) { manageState(this, line); return; } // Reset the comments buffer this.scratch = []; return; } makeDefinitionRange( name: string, line: string, search: boolean = true ): Range { let re: RegExp = new RegExp(`\\b${name}\\b`); let start: number = search ? line.search(re) : 0; let end: number = search ? start + name.length : 0; var range = positiveRange(this.lineNb, start, end); return range; } getAllMembers( items: SPItem[], kind: CompletionItemKind ): Map<string, string> { if (items == undefined) { return new Map(); } let defines = new Map(); let workspaceFolder = Workspace.getWorkspaceFolder(URI.file(this.file)); let smHome = Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>( "SourcemodHome" ) || ""; // Replace \ escaping in Windows smHome = smHome.replace(/\\/g, "/"); if (smHome === "") { return new Map(); } for (let item of items) { if (item.kind === kind) { purgeCalls(item, this.file); defines.set(item.name, item.filePath); } } return defines; } getAllMacros(items: SPItem[]): string[] { if (items == undefined) { return []; } let arr: string[] = []; for (let e of items) { if (e.kind === CompletionItemKind.Interface) { arr.push(e.name); } } return arr; } }
the_stack
import fetchMock from 'fetch-mock'; import { XAPI_ENDPOINT } from '../settings'; import { VerbDefinition } from '../types/XAPI'; import { truncateDecimalDigits } from '../utils/truncateDecimalDigits'; import { VideoXAPIStatement } from './VideoXAPIStatement'; describe('VideoXAPIStatement', () => { afterEach(() => fetchMock.reset()); describe('VideoXAPIStatement.setDuration', () => { it('does not accept negative or 0 value', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); expect(() => { xapiStatement.setDuration(-1); }).toThrowError('duration must be strictly positive'); expect(() => { xapiStatement.setDuration(0); }).toThrowError('duration must be strictly positive'); }); it('accept only one modification', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(20); expect(() => { xapiStatement.setDuration(10); }).toThrowError('duration is already set. You can not modify it anymore'); }); }); describe('VideoXAPIStatement.mergeSegments', () => { it('merges overlapping time segments', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); expect(xapiStatement.mergeSegments(['0[.]5', '10[.]22'])).toBe( '0[.]5[,]10[.]22', ); expect(xapiStatement.mergeSegments(['0[.]5', '4[.]22'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['0[.]5', '3[.]4'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['0[.]5', '22[.]10'])).toBe( '0[.]5[,]10[.]22', ); expect(xapiStatement.mergeSegments(['0[.]5', '22[.]4'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['0[.]5', '4[.]3'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['5[.]0', '10[.]22'])).toBe( '0[.]5[,]10[.]22', ); expect(xapiStatement.mergeSegments(['5[.]0', '4[.]22'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['5[.]0', '3[.]4'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['5[.]0', '22[.]10'])).toBe( '0[.]5[,]10[.]22', ); expect(xapiStatement.mergeSegments(['5[.]0', '22[.]4'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['5[.]0', '4[.]3'])).toBe('0[.]5'); // edge case tests (when start and end bounds are identical on adjacent segments) expect(xapiStatement.mergeSegments(['0[.]5', '5[.]22'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['0[.]5', '22[.]5'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['0[.]5', '3[.]5'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['0[.]5', '5[.]3'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['5[.]0', '5[.]22'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['5[.]0', '22[.]5'])).toBe('0[.]22'); expect(xapiStatement.mergeSegments(['5[.]0', '3[.]5'])).toBe('0[.]5'); expect(xapiStatement.mergeSegments(['5[.]0', '5[.]3'])).toBe('0[.]5'); // merge identical segments expect(xapiStatement.mergeSegments(['0[.]5', '0[.]5'])).toBe('0[.]5'); }); }); describe('VideoXAPIStatement.initialized', () => { it('post an initialized statement with only required extensions', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 1, }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.initialized); expect(body.verb.display).toEqual({ 'en-US': 'initialized', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 1, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body).toHaveProperty('id'); }); it('post an initialized statement with all extensions', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ ccSubtitleEnabled: true, ccSubtitleLanguage: 'en-US', frameRate: 29.97, fullScreen: false, length: 1, quality: '480', screenSize: '1080x960', speed: '1x', track: 'foo', userAgent: 'Mozilla/5.0', videoPlaybackSize: '1080x960', volume: 1, }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.initialized); expect(body.verb.display).toEqual({ 'en-US': 'initialized', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/cc-subtitle-enabled': true, 'https://w3id.org/xapi/video/extensions/cc-subtitle-lang': 'en-US', 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/frame-rate': 29.97, 'https://w3id.org/xapi/video/extensions/full-screen': false, 'https://w3id.org/xapi/video/extensions/length': 1, 'https://w3id.org/xapi/video/extensions/quality': '480', 'https://w3id.org/xapi/video/extensions/screen-size': '1080x960', 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', 'https://w3id.org/xapi/video/extensions/speed': '1x', 'https://w3id.org/xapi/video/extensions/track': 'foo', 'https://w3id.org/xapi/video/extensions/user-agent': 'Mozilla/5.0', 'https://w3id.org/xapi/video/extensions/video-playback-size': '1080x960', 'https://w3id.org/xapi/video/extensions/volume': 1, }); expect(body).toHaveProperty('id'); }); }); describe('XAPIStatement.played', () => { it('sends a played statement', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(1); xapiStatement.played({ time: 42.321, }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.played); expect(body.verb.display).toEqual({ 'en-US': 'played', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/time': 42.321, }); expect(body).toHaveProperty('id'); }); }); describe('VideoXAPIStatement.paused', () => { it('sends a paused statement without completion threshold', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(100); xapiStatement.played({ time: 0 }); xapiStatement.paused({ time: 10 }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.paused); expect(body.verb.display).toEqual({ 'en-US': 'paused', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 100, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/played-segments': '0[.]10', 'https://w3id.org/xapi/video/extensions/progress': 0.1, 'https://w3id.org/xapi/video/extensions/time': 10, }); expect(body).toHaveProperty('id'); }); }); describe('XAPIStatement.seeked', () => { it('sends a seeked statement', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(100); xapiStatement.seeked({ timeFrom: 0, timeTo: 10, }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.seeked); expect(body.verb.display).toEqual({ 'en-US': 'seeked', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/length': 100, 'https://w3id.org/xapi/video/extensions/played-segments': '10', 'https://w3id.org/xapi/video/extensions/progress': 0, 'https://w3id.org/xapi/video/extensions/time-from': 0, 'https://w3id.org/xapi/video/extensions/time-to': 10, }); expect(body).toHaveProperty('id'); }); }); describe('XAPIStatement.completed', () => { it('sends a completed statement when progress reaches 100%', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 100 }); xapiStatement.played({ time: 0 }); xapiStatement.paused({ time: 100 }); // completed is delayed to have a realistic duration const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.completed); expect(body.verb.display).toEqual({ 'en-US': 'completed', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 100, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/played-segments': '0[.]100', 'https://w3id.org/xapi/video/extensions/progress': 1, 'https://w3id.org/xapi/video/extensions/time': 100, }); expect(body.result.completion).toBe(true); expect(body.result.duration).toMatch(/^PT[0-9]*.?[0-9]*S$/); expect(body).toHaveProperty('id'); }); it('sends a completed statement even if progress is higher 100%', () => { // This test is here to reproduce a scenario found in the plyr player. // In some cases the time code sent in the last paused event, when the video // ended, can be higher than the duration sent by plyr itself. In this case // the progression is higher than 100% and if we return it the completed event // is not sent because the progression is not strictly equal to 100%. // We are not using plyr anymore but keep this test to prevent similar behavior // in other players. fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 74.582 }); xapiStatement.played({ time: 0 }); xapiStatement.paused({ time: 74.608 }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.completed); expect(body.verb.display).toEqual({ 'en-US': 'completed', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 74.582, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/played-segments': '0[.]74.608', 'https://w3id.org/xapi/video/extensions/progress': 1, 'https://w3id.org/xapi/video/extensions/time': 74.608, }); expect(body.result.completion).toBe(true); expect(body.result.duration).toMatch(/^PT[0-9]*.?[0-9]*S$/); expect(body).toHaveProperty('id'); }); }); describe('XAPIStatement.terminated', () => { it('sends terminated statement', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(100); xapiStatement.terminated({ time: 50, }); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.terminated); expect(body.verb.display).toEqual({ 'en-US': 'terminated', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 100, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/played-segments': '', 'https://w3id.org/xapi/video/extensions/progress': 0, 'https://w3id.org/xapi/video/extensions/time': 50, }); expect(body).toHaveProperty('id'); }); it('sends a terminated statement with a segment started and not closed', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(100); xapiStatement.played({ time: 0 }); xapiStatement.terminated({ time: 50, }); const calls = fetchMock.calls(`${XAPI_ENDPOINT}/video/`); const pausedCall = calls[1]; const pausedRequestParameters = pausedCall![1]!; const pausedBody = JSON.parse(pausedRequestParameters.body as string); expect(pausedBody.verb.id).toEqual(VerbDefinition.paused); expect(pausedBody.verb.display).toEqual({ 'en-US': 'paused', }); const terminatedCall = calls[2]; const requestParameters = terminatedCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.terminated); expect(body.verb.display).toEqual({ 'en-US': 'terminated', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/completion-threshold': truncateDecimalDigits(xapiStatement.getCompletionThreshold()), 'https://w3id.org/xapi/video/extensions/length': 100, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/played-segments': '0[.]50', 'https://w3id.org/xapi/video/extensions/progress': 0.5, 'https://w3id.org/xapi/video/extensions/time': 50, }); expect(body).toHaveProperty('id'); }); }); describe('XAPIStatement.interacted', () => { it('sends an interacted event with all context entensions', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(1); xapiStatement.interacted( { time: 50, }, { ccSubtitleEnabled: true, ccSubtitleLanguage: 'en', frameRate: 29.97, fullScreen: true, quality: '480', speed: '1x', track: 'foo', videoPlaybackSize: '640x480', volume: 1, }, ); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.interacted); expect(body.verb.display).toEqual({ 'en-US': 'interacted', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/cc-subtitle-enabled': true, 'https://w3id.org/xapi/video/extensions/cc-subtitle-lang': 'en', 'https://w3id.org/xapi/video/extensions/frame-rate': 29.97, 'https://w3id.org/xapi/video/extensions/full-screen': true, 'https://w3id.org/xapi/video/extensions/quality': '480', 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', 'https://w3id.org/xapi/video/extensions/speed': '1x', 'https://w3id.org/xapi/video/extensions/track': 'foo', 'https://w3id.org/xapi/video/extensions/video-playback-size': '640x480', 'https://w3id.org/xapi/video/extensions/volume': 1, }); expect(body.result.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/time': 50, }); expect(body).toHaveProperty('id'); }); }); describe('VideoXAPIStatement played segment', () => { it('computes played segment', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 100, }); expect(xapiStatement.getPlayedSegment()).toBe(''); xapiStatement.played({ time: 0 }); expect(xapiStatement.getPlayedSegment()).toBe('0'); xapiStatement.seeked({ timeFrom: 5, timeTo: 12, }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12'); xapiStatement.paused({ time: 22 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]22'); xapiStatement.seeked({ timeFrom: 22, timeTo: 15, }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]22[,]15'); xapiStatement.paused({ time: 55 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]55'); xapiStatement.played({ time: 55 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]55[,]55'); xapiStatement.paused({ time: 99.33 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]99.33'); xapiStatement.played({ time: 99.33 }); expect(xapiStatement.getPlayedSegment()).toBe( '0[.]5[,]12[.]99.33[,]99.33', ); xapiStatement.paused({ time: 100 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]100'); }); }); describe('VideoXAPIStatement.getProgress', () => { it('compute progress at random time', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 100, }); expect(xapiStatement.getPlayedSegment()).toBe(''); xapiStatement.played({ time: 0 }); expect(xapiStatement.getPlayedSegment()).toBe('0'); xapiStatement.seeked({ timeFrom: 5, timeTo: 12, }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12'); xapiStatement.paused({ time: 22 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]22'); xapiStatement.seeked({ timeFrom: 22, timeTo: 15, }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]22[,]15'); xapiStatement.paused({ time: 55 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]55'); xapiStatement.played({ time: 55 }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]5[,]12[.]55[,]55'); expect(xapiStatement.getProgress()).toEqual(0.48); }); it('compute progress when not started', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 100, }); expect(xapiStatement.getProgress()).toEqual(0); }); it('compute progress with everything watched', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.initialized({ length: 100, }); expect(xapiStatement.getPlayedSegment()).toBe(''); xapiStatement.played({ time: 0 }); expect(xapiStatement.getPlayedSegment()).toBe('0'); xapiStatement.seeked({ timeFrom: 12, timeTo: 5, }); expect(xapiStatement.getPlayedSegment()).toBe('0[.]12[,]5'); xapiStatement.paused({ time: 100 }); expect(xapiStatement.getProgress()).toEqual(1); }); }); describe('VideoXAPIStatement.computeThreshold', () => { it('return a completion thresold equal to 0.95 when time is 600', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(600); xapiStatement.computeCompletionThreshold(); expect(xapiStatement.getCompletionThreshold()).toEqual(0.95); }); it('return a completion threshold equal to 0.95 when duration is higher than 600', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(600 * (Math.random() + 1)); xapiStatement.computeCompletionThreshold(); expect(xapiStatement.getCompletionThreshold()).toEqual(0.95); }); it('return a completion closed to 0.70 when duration is less than 1 minute', () => { const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(1); xapiStatement.computeCompletionThreshold(); expect(xapiStatement.getCompletionThreshold()).toBeCloseTo(0.7, 3); }); }); describe('VideoXAPIStatement.downloaded', () => { it('sends downloaded segment', () => { fetchMock.mock(`${XAPI_ENDPOINT}/video/`, 204, { overwriteRoutes: true, }); const xapiStatement = new VideoXAPIStatement('jwt', 'abcd'); xapiStatement.setDuration(600); xapiStatement.downloaded(720); const lastCall = fetchMock.lastCall(`${XAPI_ENDPOINT}/video/`); const requestParameters = lastCall![1]!; expect(requestParameters.headers).toEqual({ Authorization: 'Bearer jwt', 'Content-Type': 'application/json', }); const body = JSON.parse(requestParameters.body as string); expect(body.verb.id).toEqual(VerbDefinition.downloaded); expect(body.verb.display).toEqual({ 'en-US': 'downloaded', }); expect(body.context.extensions).toEqual({ 'https://w3id.org/xapi/video/extensions/length': 600, 'https://w3id.org/xapi/video/extensions/quality': 720, 'https://w3id.org/xapi/video/extensions/session-id': 'abcd', }); expect(body).toHaveProperty('id'); }); }); });
the_stack
import chalk from 'chalk'; import R from 'ramda'; import BitId from '../../bit-id/bit-id'; import hasWildcard from '../../utils/string/has-wildcard'; import isBitIdMatchByWildcards from '../../utils/bit/is-bit-id-match-by-wildcards'; import { validateUserInputType } from '../../utils/validate-type'; import Component from '../component/consumer-component'; import GeneralError from '../../error/general-error'; import AbstractConfig from './abstract-config'; import { DEPENDENCIES_FIELDS, OVERRIDE_FILE_PREFIX } from '../../constants'; import logger from '../../logger/logger'; import { ComponentOverridesData } from './component-overrides'; export type ConsumerOverridesOfComponent = ComponentOverridesData & { extensions?: Record<string, any>; env?: Record<string, any>; propagate?: boolean; // whether propagate to a more general rule, defaultScope?: string; // default scope to export to defaultOwner?: string; // default scope to export to }; export type ConsumerOverridesConfig = { [key: string]: ConsumerOverridesOfComponent }; export const overridesForbiddenFields = ['name', 'main', 'version', 'bit']; export const overridesBitInternalFields = ['propagate', 'exclude', 'env', 'defaultScope', 'extensions']; export const nonPackageJsonFields = [...DEPENDENCIES_FIELDS, ...overridesBitInternalFields]; export default class ConsumerOverrides { overrides: ConsumerOverridesConfig; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! hasChanged: boolean; // whether the overrides has been changed (so then it should write them to fs) constructor(overrides: ConsumerOverridesConfig) { this.overrides = overrides; } static load(overrides: Record<string, any> = {}) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return new ConsumerOverrides(overrides); } getOverrideComponentData(bitId: BitId): ConsumerOverridesOfComponent | null | undefined { const matches = this._getAllRulesMatchedById(bitId); if (!matches.length) { return null; } const overrideValues = matches.map(match => R.clone(this.overrides[match])); let stopPropagation = false; return overrideValues.reduce((acc, current) => { if (stopPropagation) return acc; if (!current.propagate) { stopPropagation = true; } this._updateSpecificOverridesWithGeneralOverrides(current, acc); return acc; }, {}); } _updateSpecificOverridesWithGeneralOverrides( generalOverrides: Record<string, any>, specificOverrides: Record<string, any> ) { const isObjectAndNotArray = val => typeof val === 'object' && !Array.isArray(val); Object.keys(generalOverrides).forEach(field => { switch (field) { case 'env': if (!specificOverrides[field]) specificOverrides[field] = {}; ['compiler', 'tester'].forEach(envField => { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (specificOverrides.env[envField] || !generalOverrides.env[envField]) return; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! specificOverrides.env[envField] = generalOverrides.env[envField]; }); break; case 'propagate': case 'exclude': // it's a system field, do nothing break; default: if (isObjectAndNotArray(specificOverrides[field]) && isObjectAndNotArray(generalOverrides[field])) { specificOverrides[field] = Object.assign({}, generalOverrides[field], specificOverrides[field]); } else if (!specificOverrides[field]) { specificOverrides[field] = generalOverrides[field]; } // when specificOverrides[field] is set and not an object, do not override it by the general one } }); } _getAllRulesMatchedById(bitId: BitId): string[] { const exactMatch = this.findExactMatch(bitId); const matchByGlobPattern = Object.keys(this.overrides).filter(idStr => this._isMatchByWildcard(bitId, idStr)); const nonExcluded = matchByGlobPattern.filter(match => !this._isExcluded(this.overrides[match], bitId)); const allMatches = nonExcluded.sort(ConsumerOverrides.sortWildcards); if (exactMatch) allMatches.unshift(exactMatch); return allMatches; } _isMatchByWildcard(bitId: BitId, idWithPossibleWildcard: string): boolean { if (!hasWildcard(idWithPossibleWildcard)) return false; return isBitIdMatchByWildcards(bitId, idWithPossibleWildcard); } _isExcluded(overridesValues: Record<string, any>, bitId: BitId) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (!overridesValues.exclude || !overridesValues.exclude.length) { return false; } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return overridesValues.exclude.some( excludeRule => this._isMatchByWildcard(bitId, excludeRule) || bitId.toStringWithoutVersion() === excludeRule || bitId.toStringWithoutScopeAndVersion() === excludeRule ); } /** * sort from the more specific (more namespaces) to the more generic (less namespaces) * e.g. * src/utils/javascript/* * src/utils/javascript/* * src/utils/* * src/* * * more namespaces (slashes) === more specific * more wildcards === less specific * * if both have the same number of namespaces (slashes), the one with less wildcards is first. * if both have the same number of wildcards, the one with more namespaces is first. * * a reminder about compare function: * If the result is negative a is sorted before b. * If the result is positive b is sorted before a. * If the result is 0 no changes is done with the sort order of the two values. */ static sortWildcards(a: string, b: string): number { const numOfNamespaces = str => (str.match(/\//g) || []).length; const numOfWildcards = str => (str.match(/\*/g) || []).length; const indexOfFirstWildcard = str => str.indexOf('*'); const byNamespaces = numOfNamespaces(b) - numOfNamespaces(a); if (byNamespaces !== 0) return byNamespaces; const byWildcards = numOfWildcards(a) - numOfWildcards(b); if (byWildcards !== 0) return byWildcards; // both have the same number of namespaces and the same number of wildcards // e.g. a component `utils/is-string` matches two rules: `utils/*` and `*/is-string`. // the one with the wildcard more left should be first as it is more specific. return indexOfFirstWildcard(a) - indexOfFirstWildcard(b); } async updateOverridesIfChanged(component: Component, areEnvsChanged: boolean): Promise<boolean> { const overrides: ConsumerOverridesOfComponent = component.overrides.componentOverridesData; const id: BitId = component.id; const existingOverrides = this.getOverrideComponentData(id); if (!areEnvsChanged && this.areOverridesObjectsEqual(existingOverrides, overrides)) return false; const exactMatch = this.findExactMatch(id); const key = exactMatch || id.toStringWithoutVersion(); const env = {}; if (component.compiler) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! env.compiler = AbstractConfig.convertEnvToStringIfPossible(component.compiler.toBitJsonObject('.')); } if (component.tester) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! env.tester = AbstractConfig.convertEnvToStringIfPossible(component.tester.toBitJsonObject('.')); } if (!R.isEmpty(env)) overrides.env = env; this.overrides[key] = overrides; this.hasChanged = true; return true; } areOverridesObjectsEqual( overridesA: ConsumerOverridesOfComponent | null | undefined, overridesB: ConsumerOverridesOfComponent ): boolean { // seems like R.equals does a great job here. it compares objects by values (not by reference). // also it disregards the keys order. return R.equals(overridesA || {}, overridesB || {}); } findExactMatch(bitId: BitId): string | null | undefined { return Object.keys(this.overrides).find( idStr => bitId.toStringWithoutVersion() === idStr || bitId.toStringWithoutScopeAndVersion() === idStr ); } removeExactMatch(bitId: BitId): boolean { const exactMatch = this.findExactMatch(bitId); if (!exactMatch) return false; delete this.overrides[exactMatch]; return true; } static validate(overrides: Record<string, any>): void { if (typeof overrides === 'undefined') return; const message = 'consumer-config (either bit.json or package.json "bit")'; validateUserInputType(message, overrides, 'overrides', 'object'); Object.keys(overrides).forEach(id => validateComponentOverride(id, overrides[id])); function validateComponentOverride(id, override) { validateUserInputType(message, override, `overrides.${id}`, 'object'); Object.keys(override).forEach(field => { if (overridesForbiddenFields.includes(field)) { throw new GeneralError(`${message} found a forbidden field "${field}" inside "overrides.${id}" property. the following fields are not allowed: ${overridesForbiddenFields.join(', ')}.`); } if (DEPENDENCIES_FIELDS.includes(field)) { validateDependencyField(field, override, id); } else if (field === 'env') { validateEnv(override, id); } else if (field === 'exclude') { validateUserInputType(message, override.exclude, `overrides.${id}.exclude`, 'array'); } }); } function validateDependencyField(field: string, override: Record<string, any>, id: string) { validateUserInputType(message, override[field], `overrides.${id}.${field}`, 'object'); Object.keys(override[field]).forEach(rule => { validateUserInputType(message, override[field][rule], `overrides.${id}.${field}.${rule}`, 'string'); if (rule.startsWith(OVERRIDE_FILE_PREFIX)) { // @todo: once v15 is out, this warning should be replaced by an error logger.console( chalk.yellow( `warning: file overrides (using "${OVERRIDE_FILE_PREFIX}") is deprecated and will be removed on the next major version` ) ); } }); } function validateEnv(override: Record<string, any>, id: string) { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! validateUserInputType(message, override.env, `overrides.${id}.env`, 'object'); } } }
the_stack
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common'; import { JsonObject } from 'type-fest'; import head from 'lodash.head'; import last from 'lodash.last'; import { pick } from 'lodash'; import { Block as PrismaBlock, BlockVersion as PrismaBlockVersion, Prisma } from '@prisma/client'; import { PrismaService } from 'nestjs-prisma'; import { Block, BlockVersion, IBlock, BlockInputOutput, User } from 'src/models'; import { revertDeletedItemName } from 'src/util/softDelete'; import { CreateBlockArgs, UpdateBlockArgs, FindManyBlockArgs, FindManyBlockTypeArgs, CreateBlockVersionArgs, FindManyBlockVersionArgs, LockBlockArgs } from './dto'; import { FindOneArgs } from 'src/dto'; import { EnumBlockType } from 'src/enums/EnumBlockType'; import { EnumPendingChangeResourceType, EnumPendingChangeAction, PendingChange } from '../app/dto'; const CURRENT_VERSION_NUMBER = 0; const ALLOW_NO_PARENT_ONLY = new Set([null]); export type BlockPendingChange = { /** The id of the changed block */ resourceId: string; /** The type of change */ action: EnumPendingChangeAction; resourceType: EnumPendingChangeResourceType.Block; /** The block version number */ versionNumber: number; /** The block */ resource: Block; }; @Injectable() export class BlockService { constructor(private readonly prisma: PrismaService) {} /** use NULL in the set of allowed parents to allow the block to be created without a parent */ blockTypeAllowedParents: { [key in EnumBlockType]: Set<EnumBlockType | null>; } = { [EnumBlockType.ConnectorRestApiCall]: new Set([ EnumBlockType.ConnectorRestApi ]), [EnumBlockType.ConnectorRestApi]: new Set([EnumBlockType.Flow, null]), [EnumBlockType.AppSettings]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.Flow]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.ConnectorSoapApi]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.ConnectorFile]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.EntityApi]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.EntityApiEndpoint]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.FlowApi]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.Layout]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.CanvasPage]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.EntityPage]: ALLOW_NO_PARENT_ONLY, [EnumBlockType.Document]: ALLOW_NO_PARENT_ONLY }; private async resolveParentBlock( blockId: string, appId: string ): Promise<Block> { const matchingBlocks = await this.prisma.block.findMany({ where: { id: blockId, appId } }); if (matchingBlocks.length === 0) { throw new NotFoundException(`Can't find parent block with ID ${blockId}`); } if (matchingBlocks.length === 1) { const [block] = matchingBlocks; return block; } throw new Error('Unexpected length of matchingBlocks'); } async block(args: FindOneArgs): Promise<Block | null> { const block = await this.prisma.block.findFirst({ where: { id: args.where.id //deletedAt: null } }); if (!block) { throw new Error(`Cannot find block with ID ${args.where.id}`); } return block; } /** * Creates a block of specific type */ async create<T extends IBlock>( args: CreateBlockArgs & { data: CreateBlockArgs['data'] & { blockType: keyof typeof EnumBlockType }; }, user: User ): Promise<T> { const { displayName, description, app: appConnect, blockType, parentBlock: parentBlockConnect, inputParameters, outputParameters, ...settings } = args.data; let parentBlock: Block | null = null; if (parentBlockConnect?.connect?.id) { // validate that the parent block is from the same app, and that the link between the two types is allowed parentBlock = await this.resolveParentBlock( parentBlockConnect.connect.id, appConnect.connect.id ); } // validate the parent block type if ( parentBlock && !this.canUseParentType( EnumBlockType[blockType], EnumBlockType[parentBlock.blockType] ) ) { throw new ConflictException( parentBlock.blockType ? `Block type ${parentBlock.blockType} is not allowed as a parent for block type ${blockType}` : `Block type ${blockType} cannot be created without a parent block` ); } const blockData = { displayName: displayName, description: description, app: appConnect, blockType: blockType, parentBlock: parentBlockConnect, lockedAt: new Date(), lockedByUser: { connect: { id: user.id } } }; const versionData = { displayName: displayName, description: description, versionNumber: CURRENT_VERSION_NUMBER, inputParameters: { params: inputParameters }, outputParameters: { params: outputParameters }, settings }; // Create first entry on BlockVersion by default when new block is created const version = await this.prisma.blockVersion.create({ data: { ...versionData, commit: undefined, block: { create: blockData } }, include: { block: { include: { app: true, parentBlock: true } } } }); const block: IBlock = { displayName, description, blockType: blockData.blockType, id: version.block.id, createdAt: version.block.createdAt, updatedAt: version.block.updatedAt, parentBlock: version.block.parentBlock || null, versionNumber: versionData.versionNumber, inputParameters: inputParameters, outputParameters: outputParameters }; return ({ ...block, ...settings } as unknown) as T; } private versionToIBlock<T>( version: PrismaBlockVersion & { block: PrismaBlock & { parentBlock: PrismaBlock }; settings: unknown; } ): T { const { id, createdAt, updatedAt, parentBlock, displayName, description, blockType, lockedAt, lockedByUserId } = version.block; const block: IBlock = { id, createdAt, updatedAt, parentBlock, displayName, description, blockType, lockedAt, lockedByUserId, versionNumber: version.versionNumber, inputParameters: ((version.inputParameters as unknown) as { params: BlockInputOutput[]; }).params, outputParameters: ((version.outputParameters as unknown) as { params: BlockInputOutput[]; }).params }; const settings = version.settings as JsonObject; return ({ ...block, ...settings } as unknown) as T; } async findOne<T extends IBlock>(args: FindOneArgs): Promise<T | null> { const version = await this.prisma.blockVersion.findUnique({ where: { // eslint-disable-next-line @typescript-eslint/naming-convention blockId_versionNumber: { blockId: args.where.id, versionNumber: CURRENT_VERSION_NUMBER } }, include: { block: { include: { parentBlock: true } } } }); if (!version) { throw new NotFoundException( `Block with ID ${args.where.id} was not found` ); } /** @todo: add exception handling layer on the resolver level to convert to ApolloError */ return this.versionToIBlock<T>(version); } /**@todo: convert versionToIBlock */ /**@todo: return latest version number */ async findMany(args: FindManyBlockArgs): Promise<Block[]> { return this.prisma.block.findMany(args); } /**@todo: return latest version number */ /**@todo: allow sorting by version number */ async findManyByBlockType<T extends IBlock>( args: FindManyBlockTypeArgs, blockType: EnumBlockType ): Promise<T[]> { const blocks = this.prisma.block.findMany({ ...args, where: { ...args.where, blockType: { equals: blockType } }, include: { versions: { where: { versionNumber: CURRENT_VERSION_NUMBER } }, parentBlock: true } }); return (await blocks).map(block => { const [version] = block.versions; return this.versionToIBlock({ ...version, block }); }); } async createVersion(args: CreateBlockVersionArgs): Promise<BlockVersion> { const blockId = args.data.block.connect.id; const versions = await this.prisma.blockVersion.findMany({ where: { block: { id: blockId } }, orderBy: { versionNumber: Prisma.SortOrder.asc } }); const currentVersion = head(versions); // Version 0 const lastVersion = last(versions); if (!currentVersion) { throw new Error(`Block ${blockId} has no current version`); } if (!lastVersion) { throw new Error(`Block ${blockId} has no last version`); } const lastVersionNumber = lastVersion.versionNumber; const nextVersionNumber = lastVersionNumber + 1; return this.prisma.blockVersion.create({ data: { displayName: currentVersion.displayName, description: currentVersion.description, inputParameters: currentVersion.inputParameters, outputParameters: currentVersion.outputParameters, settings: currentVersion.settings, commit: { connect: { id: args.data.commit.connect.id } }, versionNumber: nextVersionNumber, block: { connect: { id: blockId } } } }); } async getVersions(args: FindManyBlockVersionArgs): Promise<BlockVersion[]> { return this.prisma.blockVersion.findMany(args); } private canUseParentType( blockType: EnumBlockType, parentType: EnumBlockType ): boolean { return this.blockTypeAllowedParents[blockType].has(parentType); } public async getParentBlock(block: { parentBlockId?: string; parentBlock?: Block; }): Promise<Block | null> { if (block.parentBlock) { return block.parentBlock; } if (!block.parentBlockId) { return null; } return this.prisma.block.findUnique({ where: { id: block.parentBlockId } }); } /** * Updates a block * Updates the name and description on the block, and the settings field on the current version * This method does not update the input or output parameters * This method does not support partial updates * */ async update<T extends IBlock>( args: UpdateBlockArgs, user: User ): Promise<T> { const { displayName, description, ...settings } = args.data; await this.acquireLock(args, user); const version = await this.prisma.blockVersion.update({ data: { settings: settings, block: { update: { displayName, description } }, displayName, description }, where: { // eslint-disable-next-line @typescript-eslint/naming-convention blockId_versionNumber: { blockId: args.where.id, versionNumber: CURRENT_VERSION_NUMBER } }, include: { block: { include: { parentBlock: true } } } }); return this.versionToIBlock<T>(version); } // Tries to acquire a lock on the given block for the given user. // The function checks that the given block is not already locked by another user // If the current user already has a lock on the block, the function complete successfully // The function also check that the given block was not "deleted". async acquireLock(args: LockBlockArgs, user: User): Promise<Block | null> { const blockId = args.where.id; const block = await this.block({ where: { id: blockId } }); if (block.lockedByUserId === user.id) { return block; } if (block.lockedByUserId) { throw new Error( `Block ${blockId} is already locked by another user - ${block.lockedByUserId} ` ); } return this.prisma.block.update({ where: { id: blockId }, data: { lockedByUser: { connect: { id: user.id } }, lockedAt: new Date() } }); } async releaseLock(blockId: string): Promise<Block | null> { return this.prisma.block.update({ where: { id: blockId }, data: { lockedByUser: { disconnect: true }, lockedAt: null } }); } /** * Gets all the blocks changed since the last app commit * @param appId the app ID to find changes to * @param userId the user ID the app ID relates to */ async getChangedBlocks( appId: string, userId: string ): Promise<BlockPendingChange[]> { const changedBlocks = await this.prisma.block.findMany({ where: { lockedByUserId: userId, appId }, include: { lockedByUser: true, versions: { orderBy: { versionNumber: Prisma.SortOrder.desc }, /**find the first two versions to decide whether it is an update or a create */ take: 2 } } }); return changedBlocks.map(block => { const [lastVersion] = block.versions; const action = block.deletedAt ? EnumPendingChangeAction.Delete : block.versions.length > 1 ? EnumPendingChangeAction.Update : EnumPendingChangeAction.Create; block.versions = undefined; /**remove the versions data - it will only be returned if explicitly asked by gql */ //prepare name fields for display if (action === EnumPendingChangeAction.Delete) { block.displayName = revertDeletedItemName(block.displayName, block.id); } return { resourceId: block.id, action: action, resourceType: EnumPendingChangeResourceType.Block, versionNumber: lastVersion.versionNumber + 1, resource: block }; }); } async getChangedBlocksByCommit(commitId: string): Promise<PendingChange[]> { const changedBlocks = await this.prisma.block.findMany({ where: { versions: { some: { commitId: commitId } } }, include: { lockedByUser: true, versions: { where: { commitId: commitId } } } }); return changedBlocks.map(block => { const [changedVersion] = block.versions; const action = changedVersion.deleted ? EnumPendingChangeAction.Delete : changedVersion.versionNumber > 1 ? EnumPendingChangeAction.Update : EnumPendingChangeAction.Create; //prepare name fields for display if (action === EnumPendingChangeAction.Delete) { block.displayName = changedVersion.displayName; } return { resourceId: block.id, action: action, resourceType: EnumPendingChangeResourceType.Block, versionNumber: changedVersion.versionNumber, resource: block }; }); } async discardPendingChanges(blockId: string, userId: string): Promise<Block> { const blockVersions = await this.prisma.blockVersion.findMany({ where: { block: { id: blockId } }, orderBy: { versionNumber: Prisma.SortOrder.asc }, include: { block: true } }); const firstBlockVersion = head(blockVersions); const lastBlockVersion = last(blockVersions); if (!firstBlockVersion || !lastBlockVersion) { throw new Error(`Block ${blockId} has no versions `); } if (firstBlockVersion.block.lockedByUserId !== userId) { throw new Error( `Cannot discard pending changes on block ${blockId} since it is not currently locked by the requesting user ` ); } await this.cloneVersionData(lastBlockVersion.id, firstBlockVersion.id); return this.releaseLock(blockId); } private async cloneVersionData( sourceVersionId: string, targetVersionId: string ): Promise<void> { const sourceVersion = await this.prisma.blockVersion.findUnique({ where: { id: sourceVersionId } }); if (!sourceVersion) { throw new Error(`Can't find source (Block Version ${sourceVersionId})`); } let targetVersion = await this.prisma.blockVersion.findUnique({ where: { id: targetVersionId } }); if (!targetVersion) { throw new Error(`Can't find target (Block Version ${targetVersionId})`); } const names = pick(sourceVersion, ['displayName', 'description']); //update the target version with its fields, and the its parent block targetVersion = await this.prisma.blockVersion.update({ where: { id: targetVersionId }, data: { //when the source target is flagged as deleted (commit on DELETE action), do not update the parent block block: sourceVersion.deleted ? undefined : { update: { ...names, deletedAt: null } }, ...names, settings: sourceVersion.settings, inputParameters: sourceVersion.inputParameters, outputParameters: sourceVersion.outputParameters } }); } }
the_stack
import type { RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import type { PreloadOptions } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads'; interface BaseToWebviewMessage { readonly __vscode_notebook_message: true; } export interface WebviewIntialized extends BaseToWebviewMessage { readonly type: 'initialized'; } export interface DimensionUpdate { readonly id: string; readonly init?: boolean; readonly height: number; readonly isOutput?: boolean; } export interface IDimensionMessage extends BaseToWebviewMessage { readonly type: 'dimension'; readonly updates: readonly DimensionUpdate[]; } export interface IMouseEnterMessage extends BaseToWebviewMessage { readonly type: 'mouseenter'; readonly id: string; } export interface IMouseLeaveMessage extends BaseToWebviewMessage { readonly type: 'mouseleave'; readonly id: string; } export interface IOutputFocusMessage extends BaseToWebviewMessage { readonly type: 'outputFocus'; readonly id: string; } export interface IOutputBlurMessage extends BaseToWebviewMessage { readonly type: 'outputBlur'; readonly id: string; } export interface IScrollToRevealMessage extends BaseToWebviewMessage { readonly type: 'scroll-to-reveal'; readonly scrollTop: number; } export interface IWheelMessage extends BaseToWebviewMessage { readonly type: 'did-scroll-wheel'; readonly payload: any; } export interface IScrollAckMessage extends BaseToWebviewMessage { readonly type: 'scroll-ack'; readonly data: { top: number; }; readonly version: number; } export interface IBlurOutputMessage extends BaseToWebviewMessage { readonly type: 'focus-editor'; readonly cellId: string; readonly focusNext?: boolean; } export interface IClickedDataUrlMessage extends BaseToWebviewMessage { readonly type: 'clicked-data-url'; readonly data: string | ArrayBuffer | null; readonly downloadName?: string; } export interface IClickMarkupCellMessage extends BaseToWebviewMessage { readonly type: 'clickMarkupCell'; readonly cellId: string; readonly ctrlKey: boolean; readonly altKey: boolean; readonly metaKey: boolean; readonly shiftKey: boolean; } export interface IContextMenuMarkupCellMessage extends BaseToWebviewMessage { readonly type: 'contextMenuMarkupCell'; readonly cellId: string; readonly clientX: number; readonly clientY: number; } export interface IMouseEnterMarkupCellMessage extends BaseToWebviewMessage { readonly type: 'mouseEnterMarkupCell'; readonly cellId: string; } export interface IMouseLeaveMarkupCellMessage extends BaseToWebviewMessage { readonly type: 'mouseLeaveMarkupCell'; readonly cellId: string; } export interface IToggleMarkupPreviewMessage extends BaseToWebviewMessage { readonly type: 'toggleMarkupPreview'; readonly cellId: string; } export interface ICellDragStartMessage extends BaseToWebviewMessage { readonly type: 'cell-drag-start'; readonly cellId: string; readonly dragOffsetY: number; } export interface ICellDragMessage extends BaseToWebviewMessage { readonly type: 'cell-drag'; readonly cellId: string; readonly dragOffsetY: number; } export interface ICellDropMessage extends BaseToWebviewMessage { readonly type: 'cell-drop'; readonly cellId: string; readonly ctrlKey: boolean; readonly altKey: boolean; readonly dragOffsetY: number; } export interface ICellDragEndMessage extends BaseToWebviewMessage { readonly type: 'cell-drag-end'; readonly cellId: string; } export interface IInitializedMarkupMessage extends BaseToWebviewMessage { readonly type: 'initializedMarkup'; } export interface IRenderedMarkupMessage extends BaseToWebviewMessage { readonly type: 'renderedMarkup'; readonly cellId: string; readonly html: string; } export interface ITelemetryFoundRenderedMarkdownMath extends BaseToWebviewMessage { readonly type: 'telemetryFoundRenderedMarkdownMath'; } export interface ITelemetryFoundUnrenderedMarkdownMath extends BaseToWebviewMessage { readonly type: 'telemetryFoundUnrenderedMarkdownMath'; readonly latexDirective: string; } export interface IClearMessage { readonly type: 'clear'; } export interface IOutputRequestMetadata { /** * Additional attributes of a cell metadata. */ readonly custom?: { [key: string]: unknown; }; } export interface IOutputRequestDto { /** * { mime_type: value } */ readonly data: { [key: string]: unknown; }; readonly metadata?: IOutputRequestMetadata; readonly outputId: string; } export type ICreationContent = | { type: RenderOutputType.Html; htmlContent: string; } | { type: RenderOutputType.Extension; outputId: string; valueBytes: Uint8Array; metadata: unknown; mimeType: string; }; export interface ICreationRequestMessage { readonly type: 'html'; readonly content: ICreationContent; readonly cellId: string; readonly outputId: string; cellTop: number; outputOffset: number; readonly left: number; readonly requiredPreloads: ReadonlyArray<IControllerPreload>; readonly initiallyHidden?: boolean; readonly rendererId?: string | undefined; } export interface IContentWidgetTopRequest { readonly cellId: string; readonly outputId: string; readonly cellTop: number; readonly outputOffset: number; readonly forceDisplay: boolean; } export interface IViewScrollTopRequestMessage { readonly type: 'view-scroll'; readonly widgets: IContentWidgetTopRequest[]; readonly markupCells: { id: string; top: number; }[]; } export interface IScrollRequestMessage { readonly type: 'scroll'; readonly id: string; readonly top: number; readonly widgetTop?: number; readonly version: number; } export interface IClearOutputRequestMessage { readonly type: 'clearOutput'; readonly cellId: string; readonly outputId: string; readonly cellUri: string; readonly rendererId: string | undefined; } export interface IHideOutputMessage { readonly type: 'hideOutput'; readonly outputId: string; readonly cellId: string; } export interface IShowOutputMessage { readonly type: 'showOutput'; readonly cellId: string; readonly outputId: string; readonly cellTop: number; readonly outputOffset: number; } export interface IFocusOutputMessage { readonly type: 'focus-output'; readonly cellId: string; } export interface IAckOutputHeight { readonly cellId: string; readonly outputId: string; readonly height: number; } export interface IAckOutputHeightMessage { readonly type: 'ack-dimension'; readonly updates: readonly IAckOutputHeight[]; } export interface IControllerPreload { readonly originalUri: string; readonly uri: string; } export interface IUpdateControllerPreloadsMessage { readonly type: 'preload'; readonly resources: IControllerPreload[]; } export interface IUpdateDecorationsMessage { readonly type: 'decorations'; readonly cellId: string; readonly addedClassNames: string[]; readonly removedClassNames: string[]; } export interface ICustomKernelMessage extends BaseToWebviewMessage { readonly type: 'customKernelMessage'; readonly message: unknown; } export interface ICustomRendererMessage extends BaseToWebviewMessage { readonly type: 'customRendererMessage'; readonly rendererId: string; readonly message: unknown; } export interface ICreateMarkupCellMessage { readonly type: 'createMarkupCell'; readonly cell: IMarkupCellInitialization; } export interface IDeleteMarkupCellMessage { readonly type: 'deleteMarkupCell'; readonly ids: readonly string[]; } export interface IHideMarkupCellMessage { readonly type: 'hideMarkupCells'; readonly ids: readonly string[]; } export interface IUnhideMarkupCellMessage { readonly type: 'unhideMarkupCells'; readonly ids: readonly string[]; } export interface IShowMarkupCellMessage { readonly type: 'showMarkupCell'; readonly id: string; readonly handle: number; readonly content: string | undefined; readonly top: number; } export interface IUpdateSelectedMarkupCellsMessage { readonly type: 'updateSelectedMarkupCells'; readonly selectedCellIds: readonly string[]; } export interface IMarkupCellInitialization { mime: string; cellId: string; cellHandle: number; content: string; offset: number; visible: boolean; } export interface IInitializeMarkupCells { readonly type: 'initializeMarkup'; readonly cells: ReadonlyArray<IMarkupCellInitialization>; } export interface INotebookStylesMessage { readonly type: 'notebookStyles'; readonly styles: { [key: string]: string; }; } export interface INotebookOptionsMessage { readonly type: 'notebookOptions'; readonly options: PreloadOptions; } export interface INotebookUpdateWorkspaceTrust { readonly type: 'updateWorkspaceTrust'; readonly isTrusted: boolean; } export type FromWebviewMessage = WebviewIntialized | IDimensionMessage | IMouseEnterMessage | IMouseLeaveMessage | IOutputFocusMessage | IOutputBlurMessage | IScrollToRevealMessage | IWheelMessage | IScrollAckMessage | IBlurOutputMessage | ICustomKernelMessage | ICustomRendererMessage | IClickedDataUrlMessage | IClickMarkupCellMessage | IContextMenuMarkupCellMessage | IMouseEnterMarkupCellMessage | IMouseLeaveMarkupCellMessage | IToggleMarkupPreviewMessage | ICellDragStartMessage | ICellDragMessage | ICellDropMessage | ICellDragEndMessage | IInitializedMarkupMessage | IRenderedMarkupMessage | ITelemetryFoundRenderedMarkdownMath | ITelemetryFoundUnrenderedMarkdownMath; export type ToWebviewMessage = IClearMessage | IFocusOutputMessage | IAckOutputHeightMessage | ICreationRequestMessage | IViewScrollTopRequestMessage | IScrollRequestMessage | IClearOutputRequestMessage | IHideOutputMessage | IShowOutputMessage | IUpdateControllerPreloadsMessage | IUpdateDecorationsMessage | ICustomKernelMessage | ICustomRendererMessage | ICreateMarkupCellMessage | IDeleteMarkupCellMessage | IShowMarkupCellMessage | IHideMarkupCellMessage | IUnhideMarkupCellMessage | IUpdateSelectedMarkupCellsMessage | IInitializeMarkupCells | INotebookStylesMessage | INotebookOptionsMessage | INotebookUpdateWorkspaceTrust; export type AnyMessage = FromWebviewMessage | ToWebviewMessage;
the_stack
import * as chai from 'chai'; const { expect } = chai; // Load chai plugins import chaiArrays = require('chai-arrays'); chai.use(chaiArrays); import chaiExclude = require('chai-exclude'); chai.use(chaiExclude); import chaiString = require('chai-string'); chai.use(chaiString); import { NormalizedCacheObject } from 'apollo-cache-inmemory'; import { ApolloClient } from 'apollo-client'; import gql from 'graphql-tag'; import * as Realm from 'realm'; import { setTimeout } from 'timers'; import { v4 } from 'uuid'; import { Credentials, GraphQLConfig, User } from '../src/index'; import { Company, generateFakeDataRealm } from './generate-fake-data'; import { GraphQLTestServer } from './GraphQLTestServer'; describe('RealmGraphQL', () => { const userId = v4(); let testServer: GraphQLTestServer; let graphQLUser: User; let serverUrl: string; let firstCompanyNameLetter: string; let lastCompanyNameLetter: string; let helper: GraphQLConfig; let testRealm: Realm; let client: ApolloClient<NormalizedCacheObject>; const ensureSynced = async (direction?: 'download' | 'upload') => { await new Promise((resolve) => setTimeout(resolve, 100)); await new Promise((resolve) => { testRealm.syncSession.addProgressNotification( direction || 'download', 'forCurrentlyOutstandingWork', (downloaded, downloadable) => { if (downloaded >= downloadable) { resolve(); } }, ); }); }; const queryCompanies = async (additionalParameters?: string, expectResults = true): Promise<Company[]> => { const result = await client.query<{companies: Company[]}>({ query: gql` query { companies${additionalParameters || ''} { companyId name address } } `, fetchPolicy: 'network-only' }); if (expectResults) { expect(result.data.companies.length).to.be.above(0); } else { expect(result.data.companies.length).to.equal(0); } return result.data.companies; }; const getCompanyCount = () => { return testRealm.objects('Company').length; }; before(async () => { testServer = new GraphQLTestServer(); await testServer.start(); serverUrl = `http://${testServer.address}`; const credentials = Credentials.nickname(userId); graphQLUser = await User.authenticate(credentials, serverUrl); }); after(async () => { await testServer.shutdown(); }); describe('full sync', () => { before(async () => { const realmCredentials = Realm.Sync.Credentials.nickname(userId); const realmUser = await Realm.Sync.User.login(serverUrl, realmCredentials); testRealm = await generateFakeDataRealm( true, `realm://${testServer.address}/${realmUser.identity}/test`, realmUser, ); await ensureSynced('upload'); firstCompanyNameLetter = testRealm.objects<Company>('Company').sorted('name')[0].name.toUpperCase()[0]; lastCompanyNameLetter = testRealm.objects<Company>('Company').sorted('name', true)[0].name.toUpperCase()[0]; // Setup the apollo client helper = await GraphQLConfig.create( graphQLUser, `/${realmUser.identity}/test` ); }); it('should have some fake data', () => { const numberOfCompanies = testRealm.objects('Company').length; expect(numberOfCompanies).to.equal(200); }); it('should specify valid graphql url', () => { expect(helper.httpEndpoint).to.equal(`http://${testServer.address}/graphql/%2F${graphQLUser.identity}%2Ftest`); }); it('should specify valid websocket url', () => { expect(helper.webSocketEndpoint).to.equal(`ws://${testServer.address}/graphql/%2F${graphQLUser.identity}%2Ftest`); }); it('should have valid authLink', () => { expect(helper.authLink).to.be.an('object'); expect(helper.authLink).to.exist; }); it('should have valid connectionParams', () => { expect(helper.connectionParams).to.be.a('function'); expect(helper.connectionParams).to.exist; expect(helper.connectionParams()).to.be.not.empty; }); describe('create a client', () => { before(() => { client = helper.createApolloClient(); }); describe('and execute query', () => { it('should return the entire dataset', async () => { const companies = await queryCompanies(); expect(companies.length).to.equal(getCompanyCount()); expect(companies).to.satisfy((value: Company[]) => { return value.every((c) => { return !!(c.name && c.address && c.companyId); }); }); }); it('should return filtered results', async () => { const companies = await queryCompanies(`(query: "name BEGINSWITH[c] '${firstCompanyNameLetter}'")`); for (const company of companies) { expect(company.name.toUpperCase()).to.startWith(firstCompanyNameLetter); } }); it('should return sorted results', async () => { const companies = await queryCompanies(`(sortBy: "name")`); const expected = companies.slice(0).sort( (prev, next) => prev.name.toUpperCase().localeCompare(next.name.toUpperCase()) ); for (let i = 0; i < companies.length; i++) { expect(companies[i].name).to.equal(expected[i].name); } expect(companies[0].name.toUpperCase()).to.startWith(firstCompanyNameLetter); }); it('should return results sorted descending', async () => { const companies = await queryCompanies(`(sortBy: "name", descending: true)`); const expected = companies.slice(0).sort( (prev, next) => next.name.toUpperCase().localeCompare(prev.name.toUpperCase()) ); for (let i = 0; i < companies.length; i++) { expect(companies[i].name).to.equal(expected[i].name); } expect(companies[0].name.toUpperCase()).to.startWith(lastCompanyNameLetter); }); it('should skip records', async () => { const companies = await queryCompanies(`(sortBy: "name", skip: 100)`); // This is a bit optimistic, but expect that the random distribution // won't be skewed toward either end. expect(companies.length).to.equal(getCompanyCount() - 100); expect(companies).to.satisfy((value: Company[]) => { return value.every((c) => { return !c.name.toUpperCase().startsWith(firstCompanyNameLetter); }); }); }); it('should limit the returned results', async () => { const companies = await queryCompanies(`(sortBy: "name", take: 100)`); expect(companies.length).to.equal(100); expect(companies[0].name.toUpperCase()).to.startWith(firstCompanyNameLetter); }); it('should paginate the result', async () => { const companies = await queryCompanies(`(sortBy: "name", skip: 90, take: 20)`); expect(companies.length).to.equal(20); expect(companies[0].name.toUpperCase()).to.not.startWith(firstCompanyNameLetter); expect(companies[19].name.toUpperCase()).to.not.startWith(lastCompanyNameLetter); }); }); describe('and execute mutation', () => { const mutationFunc = async (mutationAction: 'add' | 'update', payload: Company): Promise<Company> => { const result = await client.mutate<{result: Company}>({ mutation: gql` mutation { result: ${mutationAction}Company(input: { ${payload.companyId ? `companyId: "${payload.companyId}"` : ''} ${payload.name ? `name: "${payload.name}"` : ''} ${payload.address ? `address: "${payload.address}"` : ''} }) { companyId name address } } ` }); expect(result.data.result).to.be.ok; return result.data.result; }; const deleteFunc = async (id: string): Promise<boolean> => { const result = await client.mutate<{result: boolean}>({ mutation: gql` mutation { result: deleteCompany(companyId: "${id}") } ` }); return result.data.result; }; describe('when adding object', () => { it('should add the object', async () => { const companyId = v4(); const result = await mutationFunc('add', { companyId, name: 'ACME Inc.', address: '1 Infinite Loop' }); expect(result.companyId).to.equal(companyId); expect(result.name).to.equal('ACME Inc.'); expect(result.address).to.equal('1 Infinite Loop'); // wait for sync as realm-js doesn't have WaitForDownload yet :/ await ensureSynced(); const companyInRealm = testRealm.objectForPrimaryKey<Company>('Company', companyId); expect(companyInRealm).to.be.ok; expect(companyInRealm.name).to.equal('ACME Inc.'); expect(companyInRealm.address).to.equal('1 Infinite Loop'); }); it('should fail when properties are missing', async () => { try { await mutationFunc('add', { companyId: v4(), name: 'ACME Inc.', address: undefined }); expect.fail(undefined, undefined, 'Expected add to fail.'); } catch (e) { expect(e.message).to.contain('Company.address'); } }); it('should fail when PK is duplicate', async () => { const companyId = v4(); try { await mutationFunc('add', { companyId, name: 'foo', address: 'bar' }); await mutationFunc('add', { companyId, name: 'foo2', address: 'bar2' }); expect.fail(undefined, undefined, 'Expected add to fail with duplicate PK.'); } catch (e) { expect(e.message).to.contain(companyId).and.to.contain('existing primary key'); } }); }); describe('when updating object', () => { it('should update the object', async () => { const companyId = v4(); // Add the company that we'll update await mutationFunc('add', { companyId, name: 'should be replaced', address: 'should be replaced' }); const result = await mutationFunc('update', { companyId, name: 'Updated Inc.', address: '111 Infinite Loop' }); expect(result.companyId).to.equal(companyId); expect(result.name).to.equal('Updated Inc.'); expect(result.address).to.equal('111 Infinite Loop'); await ensureSynced(); const companyInRealm = testRealm.objectForPrimaryKey<Company>('Company', companyId); expect(companyInRealm).to.be.ok; expect(companyInRealm.name).to.equal('Updated Inc.'); expect(companyInRealm.address).to.equal('111 Infinite Loop'); }); it('should partially update the object', async () => { const companyId = v4(); // Add the company that we'll update await mutationFunc('add', { companyId, name: 'should be replaced', address: 'should remain unchanged' }); const result = await mutationFunc('update', { companyId, name: 'Partial Update Inc.', address: undefined }); expect(result.companyId).to.equal(companyId); expect(result.name).to.equal('Partial Update Inc.'); // Address should be unchanged expect(result.address).to.equal('should remain unchanged'); await ensureSynced(); const companyInRealm = testRealm.objectForPrimaryKey<Company>('Company', companyId); expect(companyInRealm).to.be.ok; expect(companyInRealm.name).to.equal('Partial Update Inc.'); expect(companyInRealm.address).to.equal('should remain unchanged'); }); }); describe('when deleting object', () => { it('should return true when successful', async () => { const companyId = v4(); // Add the company that we'll update await mutationFunc('add', { companyId, name: 'should be replaced', address: 'should be replaced' }); const result = await deleteFunc(companyId); expect(result).to.be.true; await ensureSynced(); const companyInRealm = testRealm.objectForPrimaryKey<Company>('Company', companyId); expect(companyInRealm).to.be.undefined; }); it('should return false when object doesn\'t exist', async () => { const preDeleteCount = testRealm.objects('Company').length; const result = await deleteFunc(v4()); expect(result).to.be.false; await ensureSynced(); const postDeleteCount = testRealm.objects('Company').length; expect(postDeleteCount).to.equal(preDeleteCount); }); it('should delete objects with a query', async () => { for (let i = 0; i < 10; i++) { await mutationFunc('add', { companyId: v4(), name: `deleteMe${i}`, address: 'irrelevant' }); } await ensureSynced(); const toBeDeleted = testRealm.objects('Company').filtered('name BEGINSWITH \'deleteMe\''); expect(toBeDeleted.length).to.equal(10); const response = await client.mutate<{result: number}>({ mutation: gql` mutation { result: deleteCompanies(query: "name BEGINSWITH 'deleteMe'") } ` }); expect(response.data.result).to.equal(10); await ensureSynced(); expect(toBeDeleted.length).to.equal(0); }); }); describe('when combining mutations', () => { it('should execute sequential add operations', async () => { const companyA: Company = { companyId: v4(), address: 'Some address', name: 'Sequential Company A' }; const companyB: Company = { companyId: v4(), address: 'A different address', name: 'Sequential Company B' }; const result = await client.mutate({ mutation: gql` mutation { addedCompanyA: addCompany(input: { companyId: "${companyA.companyId}" name: "${companyA.name}" address: "${companyA.address}" }) { companyId name address } addedCompanyB: addCompany(input: { companyId: "${companyB.companyId}" name: "${companyB.name}" address: "${companyB.address}" }) { companyId name address } } ` }); expect(result.data.addedCompanyA).excluding('__typename').to.deep.equal(companyA); expect(result.data.addedCompanyB).excluding('__typename').to.deep.equal(companyB); await ensureSynced(); const realmCompanyA = testRealm.objectForPrimaryKey('Company', companyA.companyId); const realmCompanyB = testRealm.objectForPrimaryKey('Company', companyB.companyId); for (const prop in companyA) { if (companyA.hasOwnProperty(prop)) { expect(realmCompanyA[prop]).to.equal(companyA[prop]); expect(realmCompanyB[prop]).to.equal(companyB[prop]); } } }); }); }); describe('and execute subscription', () => { const subscriptionFunc = async (additionalParameters?: string) => { const subscriptionData = { companies: new Array<Company>(), updates: 0, updateCompanies: (value: Company[], error: any) => { subscriptionData.updates++; if (error) { subscriptionData.error = error; } else { subscriptionData.companies.length = 0; subscriptionData.companies.push(...value); } }, error: null, observable: await client.subscribe({ query: gql` subscription { companies${additionalParameters || ''} { companyId name address } } ` }) }; subscriptionData.observable.subscribe({ next(data) { subscriptionData.updateCompanies(data.data.companies, null); }, error(value) { subscriptionData.updateCompanies(null, value); } }); await waitForSubscription(subscriptionData); return subscriptionData; }; const waitForSubscription = async (value: {updates: number, error: any}) => { const initial = value.updates; let counter = 20; while (value.updates === initial && counter > 0) { await new Promise((resolve) => setTimeout(resolve, 100)); counter--; } expect(value.error).to.be.null; }; describe('when subscribed to entire dataset', async () => { it('should update when item is added', async () => { const subscriptionData = await subscriptionFunc(); expect(subscriptionData.companies.length).to.equal(getCompanyCount()); expect(subscriptionData.companies).to.satisfy((value: Company[]) => { return value.every((c) => { return !!(c.name && c.address && c.companyId); }); }); const companyId = v4(); testRealm.write(() => { testRealm.create<Company>('Company', { companyId, address: 'Some address', name: 'Subscription company' }); }); // Not synced yet expect(subscriptionData.companies.length).to.not.equal(getCompanyCount()); await ensureSynced('upload'); await waitForSubscription(subscriptionData); expect(subscriptionData.companies.length).to.equal(getCompanyCount()); expect(subscriptionData.companies).to.satisfy( (value: Company[]) => value.some((c) => c.companyId === companyId) ); }); it('should update when item is deleted', async () => { const subscriptionData = await subscriptionFunc(); const toDeleteId = subscriptionData.companies[0].companyId; testRealm.write(() => { const toDelete = testRealm.objectForPrimaryKey('Company', toDeleteId); testRealm.delete(toDelete); }); // Not synced yet expect(subscriptionData.companies.length).to.not.equal(getCompanyCount()); await ensureSynced('upload'); await waitForSubscription(subscriptionData); expect(subscriptionData.companies.length).to.equal(getCompanyCount()); expect(subscriptionData.companies).to.satisfy( (value: Company[]) => value.every((c) => c.companyId !== toDeleteId) ); }); it('should update when item is updated', async () => { const subscriptionData = await subscriptionFunc(); const toUpdateId = subscriptionData.companies[0].companyId; testRealm.write(() => { const toUpdate = testRealm.objectForPrimaryKey<Company>('Company', toUpdateId); toUpdate.address = 'This was updated!'; }); await ensureSynced('upload'); await waitForSubscription(subscriptionData); expect(subscriptionData.companies.length).to.equal(getCompanyCount()); const updated = subscriptionData.companies.find((c) => c.companyId === toUpdateId); expect(updated.address).to.equal('This was updated!'); }); }); }); }); }); describe('partial sync', () => { before(async () => { const adminUser = await Realm.Sync.User.login(serverUrl, Realm.Sync.Credentials.nickname('admin', true)); // Create realm as reference realm before populating it const realm = await Realm.open({ sync: { url: `realm://${testServer.address}/test`, user: adminUser, fullSynchronization: false } }); realm.close(); testRealm = await generateFakeDataRealm( true, `realm://${testServer.address}/test`, adminUser, ); await ensureSynced('upload'); firstCompanyNameLetter = testRealm.objects<Company>('Company').sorted('name')[0].name.toUpperCase()[0]; lastCompanyNameLetter = testRealm.objects<Company>('Company').sorted('name', true)[0].name.toUpperCase()[0]; // Setup the apollo client helper = await GraphQLConfig.create( graphQLUser, `/test`, /* authErrorHandler */ undefined, /* isQueryBasedSync */ true, ); }); it('should specify valid graphql url', () => { expect(helper.httpEndpoint).to.equal(`http://${testServer.address}/graphql/%2Ftest%2F__partial%2F${graphQLUser.identity}%2Fgraphql-client`); }); it('should specify valid websocket url', () => { expect(helper.webSocketEndpoint).to.equal(`ws://${testServer.address}/graphql/%2Ftest%2F__partial%2F${graphQLUser.identity}%2Fgraphql-client`); }); it('should have valid authLink', () => { expect(helper.authLink).to.be.an('object'); expect(helper.authLink).to.exist; }); it('should have valid connectionParams', () => { expect(helper.connectionParams).to.be.a('function'); expect(helper.connectionParams).to.exist; expect(helper.connectionParams()).to.be.not.empty; }); describe('create a client', () => { before(() => { client = helper.createApolloClient(); }); it('subscription test', async () => { // Before a subscription - expect the Realm to be empty const companiesBeforeSubscribe = await queryCompanies(undefined, /* expectResults */ false); expect(companiesBeforeSubscribe.length).to.equal(0); const result = await client.mutate<{companies: Company[]}>({ mutation: gql` mutation { companies: createCompanySubscription { companyId name address } } ` }); expect(result.data.companies.length).to.equal(getCompanyCount()); // After subscription - expect the Realm to have data const companiesAfterSubscribe = await queryCompanies(); expect(companiesAfterSubscribe.length).to.equal(getCompanyCount()); }); }); }); });
the_stack
import * as Application from '../application'; import { Trace } from '../trace'; import type { View } from '../ui/core/view'; import { GestureTypes } from '../ui/gestures'; import { notifyAccessibilityFocusState } from './accessibility-common'; import { getAndroidAccessibilityManager } from './accessibility-service'; import { AccessibilityRole, AccessibilityState, AndroidAccessibilityEvent } from './accessibility-types'; export * from './accessibility-common'; export * from './accessibility-types'; export * from './font-scale'; let clickableRolesMap = new Set<string>(); let lastFocusedView: WeakRef<Partial<View>>; function accessibilityEventHelper(view: Partial<View>, eventType: number) { const eventName = accessibilityEventTypeMap.get(eventType); if (!isAccessibilityServiceEnabled()) { if (Trace.isEnabled()) { Trace.write(`accessibilityEventHelper: Service not active`, Trace.categories.Accessibility); } return; } if (!eventName) { Trace.write(`accessibilityEventHelper: unknown eventType: ${eventType}`, Trace.categories.Accessibility, Trace.messageType.error); return; } if (!view) { if (Trace.isEnabled()) { Trace.write(`accessibilityEventHelper: no owner: ${eventName}`, Trace.categories.Accessibility); } return; } const androidView = view.nativeViewProtected as android.view.View; if (!androidView) { if (Trace.isEnabled()) { Trace.write(`accessibilityEventHelper: no nativeView`, Trace.categories.Accessibility); } return; } switch (eventType) { case android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED: { /** * Android API >= 26 handles accessibility tap-events by converting them to TYPE_VIEW_CLICKED * These aren't triggered for custom tap events in NativeScript. */ if (android.os.Build.VERSION.SDK_INT >= 26) { // Find all tap gestures and trigger them. for (const tapGesture of view.getGestureObservers(GestureTypes.tap) ?? []) { tapGesture.callback({ android: view.android, eventName: 'tap', ios: null, object: view, type: GestureTypes.tap, view: view, }); } } return; } case android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: { const lastView = lastFocusedView?.get(); if (lastView && view !== lastView) { const lastAndroidView = lastView.nativeViewProtected as android.view.View; if (lastAndroidView) { lastAndroidView.clearFocus(); lastFocusedView = null; notifyAccessibilityFocusState(lastView, false, true); } } lastFocusedView = new WeakRef(view); notifyAccessibilityFocusState(view, true, false); return; } case android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: { const lastView = lastFocusedView?.get(); if (lastView && view === lastView) { lastFocusedView = null; androidView.clearFocus(); } notifyAccessibilityFocusState(view, false, true); return; } } } let TNSAccessibilityDelegate: android.view.View.androidviewViewAccessibilityDelegate; const androidViewToTNSView = new WeakMap<android.view.View, WeakRef<Partial<View>>>(); let accessibilityEventMap: Map<AndroidAccessibilityEvent, number>; let accessibilityEventTypeMap: Map<number, string>; function ensureNativeClasses() { if (TNSAccessibilityDelegate) { return; } // WORKAROUND: Typing refers to android.view.View.androidviewViewAccessibilityDelegate but it is called android.view.View.AccessibilityDelegate at runtime const AccessibilityDelegate: typeof android.view.View.androidviewViewAccessibilityDelegate = android.view.View['AccessibilityDelegate']; const RoleTypeMap = new Map<AccessibilityRole, string>([ [AccessibilityRole.Button, android.widget.Button.class.getName()], [AccessibilityRole.Search, android.widget.EditText.class.getName()], [AccessibilityRole.Image, android.widget.ImageView.class.getName()], [AccessibilityRole.ImageButton, android.widget.ImageButton.class.getName()], [AccessibilityRole.KeyboardKey, android.inputmethodservice.Keyboard.Key.class.getName()], [AccessibilityRole.StaticText, android.widget.TextView.class.getName()], [AccessibilityRole.Adjustable, android.widget.SeekBar.class.getName()], [AccessibilityRole.Checkbox, android.widget.CheckBox.class.getName()], [AccessibilityRole.RadioButton, android.widget.RadioButton.class.getName()], [AccessibilityRole.SpinButton, android.widget.Spinner.class.getName()], [AccessibilityRole.Switch, android.widget.Switch.class.getName()], [AccessibilityRole.ProgressBar, android.widget.ProgressBar.class.getName()], ]); clickableRolesMap = new Set<string>([AccessibilityRole.Button, AccessibilityRole.ImageButton]); const ignoreRoleTypesForTrace = new Set([AccessibilityRole.Header, AccessibilityRole.Link, AccessibilityRole.None, AccessibilityRole.Summary]); @NativeClass() class TNSAccessibilityDelegateImpl extends AccessibilityDelegate { constructor() { super(); return global.__native(this); } private getTnsView(androidView: android.view.View) { const view = androidViewToTNSView.get(androidView)?.get(); if (!view) { androidViewToTNSView.delete(androidView); return null; } return view; } public onInitializeAccessibilityNodeInfo(host: android.view.View, info: android.view.accessibility.AccessibilityNodeInfo) { super.onInitializeAccessibilityNodeInfo(host, info); const view = this.getTnsView(host); if (!view) { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${host} ${info} no tns-view`, Trace.categories.Accessibility); } return; } const accessibilityRole = view.accessibilityRole; if (accessibilityRole) { const androidClassName = RoleTypeMap.get(accessibilityRole); if (androidClassName) { const oldClassName = info.getClassName() || (android.os.Build.VERSION.SDK_INT >= 28 && host.getAccessibilityClassName()) || null; info.setClassName(androidClassName); if (Trace.isEnabled()) { Trace.write(`${view}.accessibilityRole = "${accessibilityRole}" is mapped to "${androidClassName}" (was ${oldClassName}). ${info.getClassName()}`, Trace.categories.Accessibility); } } else if (!ignoreRoleTypesForTrace.has(accessibilityRole)) { if (Trace.isEnabled()) { Trace.write(`${view}.accessibilityRole = "${accessibilityRole}" is unknown`, Trace.categories.Accessibility); } } if (clickableRolesMap.has(accessibilityRole)) { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set clickable role=${accessibilityRole}`, Trace.categories.Accessibility); } info.setClickable(true); } if (android.os.Build.VERSION.SDK_INT >= 28) { if (accessibilityRole === AccessibilityRole.Header) { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set heading role=${accessibilityRole}`, Trace.categories.Accessibility); } info.setHeading(true); } else if (host.isAccessibilityHeading()) { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set heading from host`, Trace.categories.Accessibility); } info.setHeading(true); } else { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set not heading`, Trace.categories.Accessibility); } info.setHeading(false); } } switch (accessibilityRole) { case AccessibilityRole.Switch: case AccessibilityRole.RadioButton: case AccessibilityRole.Checkbox: { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set checkable and check=${view.accessibilityState === AccessibilityState.Checked}`, Trace.categories.Accessibility); } info.setCheckable(true); info.setChecked(view.accessibilityState === AccessibilityState.Checked); break; } default: { if (Trace.isEnabled()) { Trace.write(`onInitializeAccessibilityNodeInfo ${view} - set enabled=${view.accessibilityState !== AccessibilityState.Disabled} and selected=${view.accessibilityState === AccessibilityState.Selected}`, Trace.categories.Accessibility); } info.setEnabled(view.accessibilityState !== AccessibilityState.Disabled); info.setSelected(view.accessibilityState === AccessibilityState.Selected); break; } } } if (view.accessible) { info.setFocusable(true); } } public sendAccessibilityEvent(host: android.view.ViewGroup, eventType: number) { super.sendAccessibilityEvent(host, eventType); const view = this.getTnsView(host); if (!view) { console.log(`skip - ${host} - ${accessibilityEventTypeMap.get(eventType)}`); return; } try { accessibilityEventHelper(view, eventType); } catch (err) { console.error(err); } } } TNSAccessibilityDelegate = new TNSAccessibilityDelegateImpl(); accessibilityEventMap = new Map<AndroidAccessibilityEvent, number>([ /** * Invalid selection/focus position. */ [AndroidAccessibilityEvent.INVALID_POSITION, android.view.accessibility.AccessibilityEvent.INVALID_POSITION], /** * Maximum length of the text fields. */ [AndroidAccessibilityEvent.MAX_TEXT_LENGTH, android.view.accessibility.AccessibilityEvent.MAX_TEXT_LENGTH], /** * Represents the event of clicking on a android.view.View like android.widget.Button, android.widget.CompoundButton, etc. */ [AndroidAccessibilityEvent.VIEW_CLICKED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_CLICKED], /** * Represents the event of long clicking on a android.view.View like android.widget.Button, android.widget.CompoundButton, etc. */ [AndroidAccessibilityEvent.VIEW_LONG_CLICKED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_LONG_CLICKED], /** * Represents the event of selecting an item usually in the context of an android.widget.AdapterView. */ [AndroidAccessibilityEvent.VIEW_SELECTED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_SELECTED], /** * Represents the event of setting input focus of a android.view.View. */ [AndroidAccessibilityEvent.VIEW_FOCUSED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_FOCUSED], /** * Represents the event of changing the text of an android.widget.EditText. */ [AndroidAccessibilityEvent.VIEW_TEXT_CHANGED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED], /** * Represents the event of opening a android.widget.PopupWindow, android.view.Menu, android.app.Dialog, etc. */ [AndroidAccessibilityEvent.WINDOW_STATE_CHANGED, android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED], /** * Represents the event showing a android.app.Notification. */ [AndroidAccessibilityEvent.NOTIFICATION_STATE_CHANGED, android.view.accessibility.AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED], /** * Represents the event of a hover enter over a android.view.View. */ [AndroidAccessibilityEvent.VIEW_HOVER_ENTER, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_HOVER_ENTER], /** * Represents the event of a hover exit over a android.view.View. */ [AndroidAccessibilityEvent.VIEW_HOVER_EXIT, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_HOVER_EXIT], /** * Represents the event of starting a touch exploration gesture. */ [AndroidAccessibilityEvent.TOUCH_EXPLORATION_GESTURE_START, android.view.accessibility.AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START], /** * Represents the event of ending a touch exploration gesture. */ [AndroidAccessibilityEvent.TOUCH_EXPLORATION_GESTURE_END, android.view.accessibility.AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END], /** * Represents the event of changing the content of a window and more specifically the sub-tree rooted at the event's source. */ [AndroidAccessibilityEvent.WINDOW_CONTENT_CHANGED, android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED], /** * Represents the event of scrolling a view. */ [AndroidAccessibilityEvent.VIEW_SCROLLED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_SCROLLED], /** * Represents the event of changing the selection in an android.widget.EditText. */ [AndroidAccessibilityEvent.VIEW_TEXT_SELECTION_CHANGED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED], /** * Represents the event of an application making an announcement. */ [AndroidAccessibilityEvent.ANNOUNCEMENT, android.view.accessibility.AccessibilityEvent.TYPE_ANNOUNCEMENT], /** * Represents the event of gaining accessibility focus. */ [AndroidAccessibilityEvent.VIEW_ACCESSIBILITY_FOCUSED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED], /** * Represents the event of clearing accessibility focus. */ [AndroidAccessibilityEvent.VIEW_ACCESSIBILITY_FOCUS_CLEARED, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED], /** * Represents the event of traversing the text of a view at a given movement granularity. */ [AndroidAccessibilityEvent.VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, android.view.accessibility.AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY], /** * Represents the event of beginning gesture detection. */ [AndroidAccessibilityEvent.GESTURE_DETECTION_START, android.view.accessibility.AccessibilityEvent.TYPE_GESTURE_DETECTION_START], /** * Represents the event of ending gesture detection. */ [AndroidAccessibilityEvent.GESTURE_DETECTION_END, android.view.accessibility.AccessibilityEvent.TYPE_GESTURE_DETECTION_END], /** * Represents the event of the user starting to touch the screen. */ [AndroidAccessibilityEvent.TOUCH_INTERACTION_START, android.view.accessibility.AccessibilityEvent.TYPE_TOUCH_INTERACTION_START], /** * Represents the event of the user ending to touch the screen. */ [AndroidAccessibilityEvent.TOUCH_INTERACTION_END, android.view.accessibility.AccessibilityEvent.TYPE_TOUCH_INTERACTION_END], /** * Mask for AccessibilityEvent all types. */ [AndroidAccessibilityEvent.ALL_MASK, android.view.accessibility.AccessibilityEvent.TYPES_ALL_MASK], ]); accessibilityEventTypeMap = new Map([...accessibilityEventMap].map(([k, v]) => [v, k])); } let accessibilityStateChangeListener: androidx.core.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener; let touchExplorationStateChangeListener: androidx.core.view.accessibility.AccessibilityManagerCompat.TouchExplorationStateChangeListener; function updateAccessibilityServiceState() { const accessibilityManager = getAndroidAccessibilityManager(); if (!accessibilityManager) { return; } accessibilityServiceEnabled = !!accessibilityManager.isEnabled() && !!accessibilityManager.isTouchExplorationEnabled(); } let accessibilityServiceEnabled: boolean; export function isAccessibilityServiceEnabled(): boolean { if (typeof accessibilityServiceEnabled === 'boolean') { return accessibilityServiceEnabled; } const accessibilityManager = getAndroidAccessibilityManager(); accessibilityStateChangeListener = new androidx.core.view.accessibility.AccessibilityManagerCompat.AccessibilityStateChangeListener({ onAccessibilityStateChanged(enabled) { updateAccessibilityServiceState(); if (Trace.isEnabled()) { Trace.write(`AccessibilityStateChangeListener state changed to: ${!!enabled}`, Trace.categories.Accessibility); } }, }); touchExplorationStateChangeListener = new androidx.core.view.accessibility.AccessibilityManagerCompat.TouchExplorationStateChangeListener({ onTouchExplorationStateChanged(enabled) { updateAccessibilityServiceState(); if (Trace.isEnabled()) { Trace.write(`TouchExplorationStateChangeListener state changed to: ${!!enabled}`, Trace.categories.Accessibility); } }, }); androidx.core.view.accessibility.AccessibilityManagerCompat.addAccessibilityStateChangeListener(accessibilityManager, accessibilityStateChangeListener); androidx.core.view.accessibility.AccessibilityManagerCompat.addTouchExplorationStateChangeListener(accessibilityManager, touchExplorationStateChangeListener); updateAccessibilityServiceState(); Application.on(Application.exitEvent, (args: Application.ApplicationEventData) => { const activity = args.android as android.app.Activity; if (activity && !activity.isFinishing()) { return; } const accessibilityManager = getAndroidAccessibilityManager(); if (accessibilityManager) { if (accessibilityStateChangeListener) { androidx.core.view.accessibility.AccessibilityManagerCompat.removeAccessibilityStateChangeListener(accessibilityManager, accessibilityStateChangeListener); } if (touchExplorationStateChangeListener) { androidx.core.view.accessibility.AccessibilityManagerCompat.removeTouchExplorationStateChangeListener(accessibilityManager, touchExplorationStateChangeListener); } } accessibilityStateChangeListener = null; touchExplorationStateChangeListener = null; Application.off(Application.resumeEvent, updateAccessibilityServiceState); }); Application.on(Application.resumeEvent, updateAccessibilityServiceState); return accessibilityServiceEnabled; } export function setupAccessibleView(view: Partial<View>): void { updateAccessibilityProperties(view); } export function updateAccessibilityProperties(view: Partial<View>): void { if (!view.nativeViewProtected) { return; } setAccessibilityDelegate(view); applyContentDescription(view); } export function sendAccessibilityEvent(view: View, eventType: AndroidAccessibilityEvent, text?: string): void { if (!isAccessibilityServiceEnabled()) { return; } const cls = `sendAccessibilityEvent(${view}, ${eventType}, ${text})`; const androidView = view.nativeViewProtected as android.view.View; if (!androidView) { if (Trace.isEnabled()) { Trace.write(`${cls}: no nativeView`, Trace.categories.Accessibility); } return; } if (!eventType) { if (Trace.isEnabled()) { Trace.write(`${cls}: no eventName provided`, Trace.categories.Accessibility); } return; } if (!isAccessibilityServiceEnabled()) { if (Trace.isEnabled()) { Trace.write(`${cls} - TalkBack not enabled`, Trace.categories.Accessibility); } return; } const accessibilityManager = getAndroidAccessibilityManager(); if (!accessibilityManager?.isEnabled()) { if (Trace.isEnabled()) { Trace.write(`${cls} - accessibility service not enabled`, Trace.categories.Accessibility); } return; } if (!accessibilityEventMap.has(eventType)) { if (Trace.isEnabled()) { Trace.write(`${cls} - unknown event`, Trace.categories.Accessibility); } return; } const eventInt = accessibilityEventMap.get(eventType); if (!text) { return androidView.sendAccessibilityEvent(eventInt); } const accessibilityEvent = android.view.accessibility.AccessibilityEvent.obtain(eventInt); accessibilityEvent.setSource(androidView); accessibilityEvent.getText().clear(); if (!text) { applyContentDescription(view); text = androidView.getContentDescription() || view['title']; if (Trace.isEnabled()) { Trace.write(`${cls} - text not provided use androidView.getContentDescription() - ${text}`, Trace.categories.Accessibility); } } if (Trace.isEnabled()) { Trace.write(`${cls}: send event with text: '${JSON.stringify(text)}'`, Trace.categories.Accessibility); } if (text) { accessibilityEvent.getText().add(text); } accessibilityManager.sendAccessibilityEvent(accessibilityEvent); } export function updateContentDescription(view: View, forceUpdate?: boolean): string | null { if (!view.nativeViewProtected) { return; } return applyContentDescription(view, forceUpdate); } function setAccessibilityDelegate(view: Partial<View>): void { if (!view.nativeViewProtected) { return; } ensureNativeClasses(); const androidView = view.nativeViewProtected as android.view.View; if (!androidView || !androidView.setAccessibilityDelegate) { return; } androidViewToTNSView.set(androidView, new WeakRef(view)); let hasOldDelegate = false; if (typeof androidView.getAccessibilityDelegate === 'function') { hasOldDelegate = androidView.getAccessibilityDelegate() === TNSAccessibilityDelegate; } if (hasOldDelegate) { return; } androidView.setAccessibilityDelegate(TNSAccessibilityDelegate); } function applyContentDescription(view: Partial<View>, forceUpdate?: boolean) { let androidView = view.nativeViewProtected as android.view.View; if (!androidView) { return; } if (androidView instanceof androidx.appcompat.widget.Toolbar) { const numChildren = androidView.getChildCount(); for (let i = 0; i < numChildren; i += 1) { const childAndroidView = androidView.getChildAt(i); if (childAndroidView instanceof androidx.appcompat.widget.AppCompatTextView) { androidView = childAndroidView; break; } } } const cls = `applyContentDescription(${view})`; if (!androidView) { return null; } const titleValue = view['title'] as string; const textValue = view['text'] as string; if (!forceUpdate && view._androidContentDescriptionUpdated === false && textValue === view['_lastText'] && titleValue === view['_lastTitle']) { // prevent updating this too much return androidView.getContentDescription(); } const contentDescriptionBuilder = new Array<string>(); // Workaround: TalkBack won't read the checked state for fake Switch. if (view.accessibilityRole === AccessibilityRole.Switch) { const androidSwitch = new android.widget.Switch(Application.android.context); if (view.accessibilityState === AccessibilityState.Checked) { contentDescriptionBuilder.push(androidSwitch.getTextOn()); } else { contentDescriptionBuilder.push(androidSwitch.getTextOff()); } } if (view.accessibilityLabel) { if (Trace.isEnabled()) { Trace.write(`${cls} - have accessibilityLabel`, Trace.categories.Accessibility); } contentDescriptionBuilder.push(`${view.accessibilityLabel}`); } if (view.accessibilityValue) { if (Trace.isEnabled()) { Trace.write(`${cls} - have accessibilityValue`, Trace.categories.Accessibility); } contentDescriptionBuilder.push(`${view.accessibilityValue}`); } else if (textValue) { if (textValue !== view.accessibilityLabel) { if (Trace.isEnabled()) { Trace.write(`${cls} - don't have accessibilityValue - use 'text' value`, Trace.categories.Accessibility); } contentDescriptionBuilder.push(`${textValue}`); } } else if (titleValue) { if (titleValue !== view.accessibilityLabel) { if (Trace.isEnabled()) { Trace.write(`${cls} - don't have accessibilityValue - use 'title' value`, Trace.categories.Accessibility); } contentDescriptionBuilder.push(`${titleValue}`); } } if (view.accessibilityHint) { if (Trace.isEnabled()) { Trace.write(`${cls} - have accessibilityHint`, Trace.categories.Accessibility); } contentDescriptionBuilder.push(`${view.accessibilityHint}`); } const contentDescription = contentDescriptionBuilder.join('. ').trim().replace(/^\.$/, ''); if (contentDescription) { if (Trace.isEnabled()) { Trace.write(`${cls} - set to "${contentDescription}"`, Trace.categories.Accessibility); } androidView.setContentDescription(contentDescription); } else { if (Trace.isEnabled()) { Trace.write(`${cls} - remove value`, Trace.categories.Accessibility); } androidView.setContentDescription(null); } view['_lastTitle'] = titleValue; view['_lastText'] = textValue; view._androidContentDescriptionUpdated = false; return contentDescription; }
the_stack
import Logger from "@src/lib/logging" import * as DOM from "@src/lib/dom" import * as hinting from "@src/content/hinting" /** * Open mode: how to act on the selected hintable element */ export enum OpenMode { Default = "", Tab = "-t", BackgroundTab = "-b", Window = "-w", WindowPrivate = "-wp", Highlight = "-h", Images = "-i", ImagesTab = "-I", Kill = "-k", KillTridactyl = "-K", Scroll = "-z", SaveResource = "-s", SaveImage = "-S", SaveAsResource = "-a", SaveAsImage = "-A", ScrollFocus = "-;", TTSRead = "-r", YankAlt = "-P", YankAnchor = "-#", YankLink = "-y", YankText = "-p", } /** * Hinting parameters interface */ export interface HintOptions { rapid: boolean textFilter: null | string | RegExp openMode: OpenMode includeInvisible: boolean immediate: boolean jshints: boolean callback: null | string excmd: null | string pipeAttribute: null | string selectors: string[] warnings: string[] } /** * Hinting parameters class for parsing */ export class HintConfig implements HintOptions { public rapid = false public textFilter = null public openMode = OpenMode.Default public includeInvisible = false public immediate = false public jshints = true public callback = null public excmd = null public pipeAttribute = null public selectors = [] public warnings = [] public static parse(args: string[]): HintConfig { // Argument parser state enum State { Initial, ExpectF, ExpectFR, ExpectCallback, ExpectExcmd, ExpectSelector, ExpectPipeSelector, ExpectPipeAttribute, ExpectSelectorCallback, } const result = new HintConfig() const multiLetterFlags = ["fr", "wp", "br", "pipe"] // Parser state let state = State.Initial outer: for (let argI = 0; argI < args.length; ++argI) { const arg = args[argI] switch (state) { case State.Initial: if (arg.length >= 2 && arg[0] === "-" && arg[1] !== "-") { // Parse short arguments, i.e. - followed by (mostly) single-letter arguments, // and some two-letter arguments. for (let i = 1; i < arg.length; ++i) { let flag = arg[i] // Fix two-letter flags using lookahead if (i < arg.length - 1) { const multiLetterFlag = multiLetterFlags.find( tlf => arg.substring(i, i + tlf.length) === tlf, ) if (multiLetterFlag !== undefined) { flag = multiLetterFlag i += multiLetterFlag.length - 1 } } // Process flag let newOpenMode: undefined | OpenMode let newState: undefined | State // eslint-disable-next-line sonarjs/max-switch-cases switch (flag) { case "br": // Equivalent to -qb, but deprecated result.rapid = true newOpenMode = OpenMode.BackgroundTab break case "q": result.rapid = true break case "f": newState = State.ExpectF break case "fr": newState = State.ExpectFR break case "V": result.includeInvisible = true break case "J": result.jshints = false break case "!": result.immediate = true break case "F": newState = State.ExpectCallback break case "W": newState = State.ExpectExcmd break case "c": newState = State.ExpectSelector break case "pipe": newState = State.ExpectPipeSelector break case "t": newOpenMode = OpenMode.Tab break case "b": newOpenMode = OpenMode.BackgroundTab break case "w": newOpenMode = OpenMode.Window break case "wp": newOpenMode = OpenMode.WindowPrivate break case "h": newOpenMode = OpenMode.Highlight break case "i": newOpenMode = OpenMode.Images break case "I": newOpenMode = OpenMode.ImagesTab break case "k": newOpenMode = OpenMode.Kill break case "K": newOpenMode = OpenMode.KillTridactyl break case "z": newOpenMode = OpenMode.Scroll break case "s": newOpenMode = OpenMode.SaveResource break case "S": newOpenMode = OpenMode.SaveImage break case "a": newOpenMode = OpenMode.SaveAsResource break case "A": newOpenMode = OpenMode.SaveAsImage break case ";": newOpenMode = OpenMode.ScrollFocus break case "r": newOpenMode = OpenMode.TTSRead break case "P": newOpenMode = OpenMode.YankAlt break case "#": newOpenMode = OpenMode.YankAnchor break case "y": newOpenMode = OpenMode.YankLink break case "p": newOpenMode = OpenMode.YankText break default: result.warnings.push( `unknown flag -${flag}`, ) break } // Check openMode changes if (newOpenMode !== undefined) { if (result.openMode !== OpenMode.Default) { // Notify that multiple open modes doesn't make sense result.warnings.push( "multiple open mode flags specified, overriding the previous ones", ) } result.openMode = newOpenMode } // Check state changes if (newState !== undefined) { // Some state transitions are dubious, specifically all the ones that go from (argument // expecting value) to (other argument expecting value), except for -cF if ( (state === State.ExpectSelector && newState === State.ExpectCallback) || (state === State.ExpectCallback && newState === State.ExpectSelector) ) { newState = State.ExpectSelectorCallback } if ( state !== State.Initial && newState !== State.ExpectSelectorCallback ) { result.warnings.push( `multiple flags taking a value were specified, only the last one (-${flag}) will be processed`, ) } state = newState } } } else { // Not something that looks like an argument, add it to positionals for later processing result.selectors.push(arg) } break case State.ExpectF: case State.ExpectFR: // Collect arguments using escapes let filter = arg while (filter.endsWith("\\")) { filter = filter.substring(0, filter.length - 1) if (argI + 1 < args.length) { filter += " " + args[++argI] } else { break } } if (state == State.ExpectF) { // -f result.textFilter = filter } else { // -fr result.textFilter = new RegExp(filter) } state = State.Initial break case State.ExpectExcmd: // Collect all the remaining arguments into a excmd callback result.excmd = args.slice(argI).join(" ") // Reset state to initial, parsing was successful state = State.Initial break outer case State.ExpectCallback: // Collect all the remaining arguments into a Javascript callback result.callback = args.slice(argI).join(" ") // Reset state to initial, parsing was successful state = State.Initial break outer case State.ExpectSelector: // -c, expect a single selector result.selectors.push(arg) state = State.Initial break case State.ExpectPipeSelector: // -pipe, first expect a selector result.selectors.push(arg) // Then, expect the attribute state = State.ExpectPipeAttribute break case State.ExpectPipeAttribute: // -pipe, second argument result.pipeAttribute = arg // Keep parsing options when we're done state = State.Initial break case State.ExpectSelectorCallback: // -cF, expect selector, then callback result.selectors.push(arg) state = State.ExpectCallback break } } if (state !== State.Initial) { // If we didn't return to the initial state, we were expecting an option value result.warnings.push("error parsing options: expected a value") } return result } public printWarnings(logger: Logger) { for (const warning of this.warnings) { logger.warning(warning) } } defaultHintables() { // Use the default selectors to find hintable elements switch (this.openMode) { case OpenMode.YankText: case OpenMode.Highlight: case OpenMode.Scroll: // For text-based opens, look for elements with text by default return hinting.toHintablesArray( DOM.elementsWithText(this.includeInvisible), ) case OpenMode.YankAlt: return hinting.toHintablesArray( DOM.getElemsBySelector("[title],[alt]", [ DOM.isVisibleFilter(this.includeInvisible), ]), ) case OpenMode.YankAnchor: return hinting.toHintablesArray( DOM.anchors(this.includeInvisible), ) case OpenMode.Images: case OpenMode.ImagesTab: case OpenMode.SaveImage: case OpenMode.SaveAsImage: return hinting.toHintablesArray( hinting.hintableImages(this.includeInvisible), ) case OpenMode.Kill: case OpenMode.KillTridactyl: return hinting.toHintablesArray( hinting.killables(this.includeInvisible), ) case OpenMode.SaveResource: case OpenMode.SaveAsResource: return hinting.toHintablesArray( hinting.saveableElements(this.includeInvisible), ) default: return hinting.hintables( DOM.HINTTAGS_selectors, this.jshints, this.includeInvisible, ) } } public hintables() { // User selectors always override default built-ins const hintables = this.selectors.length > 0 ? hinting.hintables( this.selectors.join(" "), this.jshints, this.includeInvisible, ) : this.defaultHintables() // Do we have text filters to refine this? if (this.textFilter !== null) { for (const elements of hintables) { elements.elements = elements.elements.filter( hinting.hintByTextFilter(this.textFilter), ) } } return hintables } public get isYank() { return ( this.openMode === OpenMode.YankAnchor || this.openMode === OpenMode.YankAlt || this.openMode === OpenMode.YankLink || this.openMode === OpenMode.YankText ) } }
the_stack
* ------------------------------------------------------------------------------ * Requirements * ------------------------------------------------------------------------------ */ import { promisify } from 'util'; import * as zlib from 'zlib'; import { asyncTry, getFileExtension, isTextMediaType } from '@hint/utils'; import { normalizeString } from '@hint/utils-string'; import { HttpHeaders } from '@hint/utils-types'; import { HTMLElement } from '@hint/utils-dom'; import { isHTTP, isRegularProtocol, normalizeHeaderValue } from '@hint/utils-network'; import { FetchEnd, HintContext, IHint, NetworkData, Response } from 'hint'; import { Severity } from '@hint/utils-types'; import { CompressionCheckOptions } from './types'; import meta from './meta'; import { getMessage } from './i18n.import'; const decompressBrotli = promisify(zlib.brotliDecompress) as (buffer: Buffer) => Promise<Buffer>; const uaString = 'Mozilla/5.0 Gecko'; /* * ------------------------------------------------------------------------------ * Public * ------------------------------------------------------------------------------ */ export default class HttpCompressionHint implements IHint { public static readonly meta = meta; public constructor(context: HintContext) { const getHintOptions = (property: string): CompressionCheckOptions => { return { brotli: true, gzip: true, threshold: 1024, zopfli: true, ...(context.hintOptions && context.hintOptions[property]) }; }; const resourceOptions: CompressionCheckOptions = getHintOptions('resource'); const htmlOptions: CompressionCheckOptions = getHintOptions('html'); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const isBigFile = (size: number, options: CompressionCheckOptions) => { return size > options.threshold; }; const checkIfBytesMatch = (rawResponse: Buffer, magicNumbers: number[]) => { return rawResponse && magicNumbers.every((b, i) => { return rawResponse[i] === b; }); }; const getHeaderValues = (headers: HttpHeaders, headerName: string) => { return (normalizeHeaderValue(headers, headerName) || '').split(','); }; const checkVaryHeader = (resource: string, headers: HttpHeaders) => { const varyHeaderValues = getHeaderValues(headers, 'vary'); const cacheControlValues = getHeaderValues(headers, 'cache-control'); if (!cacheControlValues.includes('private') && !varyHeaderValues.includes('accept-encoding')) { let codeSnippet = ''; if (varyHeaderValues.length > 0) { codeSnippet = `Vary: ${varyHeaderValues.join(',')}\n`; } if (cacheControlValues.length > 0) { codeSnippet += `Cache-Control: ${cacheControlValues.join(',')}`; } context.report( resource, getMessage('responseShouldIncludeVary', context.language), { codeLanguage: 'http', codeSnippet: codeSnippet.trim(), severity: Severity.warning } ); } }; const generateDisallowedCompressionMessage = (encoding: string) => { return getMessage('responseShouldNotBeCompressed', context.language, encoding); }; const generateContentEncodingMessage = (encoding: string) => { return getMessage('responseShouldIncludeContentEncoding', context.language, encoding); }; const generateGzipCompressionMessage = (encoding: string) => { return getMessage('responseShouldBeCompressedGzip', context.language, encoding); }; const generateSizeMessage = (resource: string, element: HTMLElement | null, encoding: string, sizeDifference: number) => { if (sizeDifference > 0) { context.report( resource, getMessage('responseBiggerThan', context.language, encoding), { element, severity: Severity.warning } ); } else { context.report( resource, getMessage('responseSameSize', context.language, encoding), { element, severity: Severity.hint } ); } }; const getNetworkData = async (resource: string, requestHeaders: HttpHeaders) => { const safeFetch = asyncTry<NetworkData>(context.fetchContent.bind(context)); const networkData: NetworkData | null = await safeFetch(resource, requestHeaders); if (!networkData) { return null; } const safeRawResponse = asyncTry<Buffer>(networkData.response.body.rawResponse.bind(networkData.response.body)); const rawResponse: Buffer | null = await safeRawResponse(); if (!rawResponse) { return null; } return { contentEncodingHeaderValue: normalizeHeaderValue(networkData.response.headers, 'content-encoding'), rawContent: networkData.response.body.rawContent, rawResponse, response: networkData.response }; }; const isCompressedWithBrotli = async (rawResponse: Buffer): Promise<boolean> => { /* * Brotli doesn't currently contain any magic numbers. * https://github.com/google/brotli/issues/298#issuecomment-172549140 */ try { const decompressedContent = await decompressBrotli(rawResponse); if (decompressedContent.byteLength === 0 && rawResponse.byteLength !== 0) { return false; } } catch (e) { return false; } return true; }; const isCompressedWithGzip = (rawContent: Buffer): boolean => { // See: https://tools.ietf.org/html/rfc1952#page-5. return checkIfBytesMatch(rawContent, [0x1f, 0x8b]); }; const isNotCompressedWithZopfli = (rawResponse: Buffer): boolean => { /* * Since the Zopfli output (for the gzip option) is valid * gzip content, there doesn't seem to be a straightforward * and foolproof way to identify files compressed with Zopfli. * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * From an email discussion with @lvandeve: * * " There is no way to tell for sure. Adding information * to the output to indicate zopfli, would actually * add bits to the output so such thing is not done :) * Any compressor can set the FLG, MTIME, and so on * to anything it wants, and users of zopfli can also * change the MTIME bytes that zopfli had output to an * actual time. * * One heuristic to tell that it was compressed with * zopfli or another dense deflate compressor is to * compress it with regular gzip -9 (which is fast), * and compare that the size of the file to test is * for example more than 3% smaller. " * * Using the above mentioned for every resource `hint` * encounters can be expensive, plus, for the online scanner, * it might also cause some security (?) problems. * * So, since this is not a foolproof way to identify files * compressed with Zopfli, the following still not foolproof, * but faster way is used. * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * 1. gzip * * A gzip member header has the following structure * * +---+---+---+---+---+---+---+---+---+---+ * |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) * +---+---+---+---+---+---+---+---+---+---+ * * where: * * ID1 = 1f and ID2 = 8b - these are the magic * numbers that uniquely identify the content * as being gzip. * * CM = 8 - this is a value customarily used by gzip * * FLG and MTIME are usually non-zero values. * * XFL will be either 0, 2, or 4: * * 0 - default, compressor used intermediate levels * of compression (when any of the -2 ... -8 * options are used). * * 2 - the compressor used maximum compression, * slowest algorithm (when the -9 or --best * option is used). * * 4 - the compressor used fastest algorithm (when * the -1 or --fast option is used). * * 2. Zopfli * * One thing that Zopfli does is that it sets FLG and * MTIME to 0, XFL to 2, and OS to 3 [1], so basically * files compressed with Zopfli will most likely start * with `1f8b 0800 0000 0000 0203`, unless things are * changed by the user (which in general doesn't seem * very likely to happen). * * Now, regular gzip output might also start with that, * even thought the chance of doing so is smaller: * * * Most web servers (e.g.: Apache², NGINX³), by default, * will not opt users into the best compression level, * therefore, the output shouldn't have XFL set to 2. * * * Most utilities that output regular gzip will have * non-zero values for MTIME and FLG. * * So, if a file does not start with: * * `1f8b 0800 0000 0000 0203` * * it's a good (not perfect) indication that Zopfli wasn't * used, but it's a fast check compared to compressing * files and comparing file sizes. However, if a file does * start with that, it can be either Zopfli or gzip, and * we cannot really make assumptions here. * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * Ref: * * ¹ https://github.com/google/zopfli/blob/6818a0859063b946094fb6f94732836404a0d89a/src/zopfli/gzip_container.c#L90-L101) * ² https://httpd.apache.org/docs/current/mod/mod_deflate.html#DeflateCompressionLevel * ³ https://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_comp_level */ return !checkIfBytesMatch(rawResponse, [0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03]); }; const checkBrotli = async (resource: string, element: HTMLElement | null, options: CompressionCheckOptions) => { let networkData = await getNetworkData(resource, { 'Accept-Encoding': 'br' }); if (!networkData) { context.report( resource, getMessage('couldNotBeFetchedBrotli', context.language), { element, severity: Severity.error } ); return; } const { contentEncodingHeaderValue, rawResponse, response } = networkData; const compressedWithBrotli = await isCompressedWithBrotli(rawResponse); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check if compressed with Brotli over HTTP. if (isHTTP(resource)) { if (compressedWithBrotli) { context.report( resource, getMessage('noCompressedBrotliOverHTTP', context.language), { element, severity: Severity.warning } ); } return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check compressed vs. uncompressed sizes. /* * TODO: Remove the following once connectors * support Brotli compression. */ const rawContent = compressedWithBrotli ? await decompressBrotli(rawResponse) : response.body.rawContent; const itShouldNotBeCompressed = contentEncodingHeaderValue === 'br' && rawContent.byteLength <= rawResponse.byteLength; if (compressedWithBrotli && itShouldNotBeCompressed) { generateSizeMessage(resource, element, 'Brotli', rawResponse.byteLength - rawContent.byteLength); return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check if compressed. if (!compressedWithBrotli) { context.report( resource, getMessage('compressedWithBrotliOverHTTPS', context.language), { element, severity: isBigFile(rawResponse.byteLength, options) ? Severity.warning : Severity.hint } ); return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check related headers. checkVaryHeader(resource, response.headers); if (contentEncodingHeaderValue !== 'br') { context.report( resource, generateContentEncodingMessage('br'), { element, severity: Severity.error } ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check for user agent sniffing. networkData = await getNetworkData(resource, { 'Accept-Encoding': 'br', 'User-Agent': uaString }); if (!networkData) { context.report( resource, getMessage('couldNotBeFetchedBrotli', context.language), { element, severity: Severity.error }); return; } const { rawResponse: uaRawResponse } = networkData; if (!(await isCompressedWithBrotli(uaRawResponse))) { context.report( resource, getMessage('compressedWithBrotliOverHTTPSAgent', context.language), { element, severity: Severity.warning } ); } }; const checkGzipZopfli = async (resource: string, element: HTMLElement | null, shouldCheckIfCompressedWith: CompressionCheckOptions) => { let networkData = await getNetworkData(resource, { 'Accept-Encoding': 'gzip' }); if (!networkData) { context.report( resource, getMessage('couldNotBeFetchedGzip', context.language), { element, severity: Severity.error } ); return; } const { contentEncodingHeaderValue, rawContent, rawResponse, response } = networkData; const compressedWithGzip = isCompressedWithGzip(rawResponse); const notCompressedWithZopfli = isNotCompressedWithZopfli(rawResponse); const itShouldNotBeCompressed = contentEncodingHeaderValue === 'gzip' && rawContent.byteLength <= rawResponse.byteLength; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check compressed vs. uncompressed sizes. if (compressedWithGzip && itShouldNotBeCompressed) { generateSizeMessage(resource, element, notCompressedWithZopfli ? 'gzip' : 'Zopfli', rawResponse.byteLength - rawContent.byteLength); return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check if compressed. if (!compressedWithGzip && shouldCheckIfCompressedWith.gzip) { context.report( resource, generateGzipCompressionMessage('gzip'), { element, severity: isBigFile(rawResponse.byteLength, shouldCheckIfCompressedWith) ? Severity.error : Severity.hint }); return; } if (notCompressedWithZopfli && shouldCheckIfCompressedWith.zopfli) { context.report( resource, generateGzipCompressionMessage('Zopfli'), { element, severity: Severity.hint } ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check related headers. if (shouldCheckIfCompressedWith.gzip || shouldCheckIfCompressedWith.zopfli) { checkVaryHeader(resource, response.headers); if (contentEncodingHeaderValue !== 'gzip') { context.report( resource, generateContentEncodingMessage('gzip'), { element, severity: Severity.error } ); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Check for user agent sniffing. networkData = await getNetworkData(resource, { 'Accept-Encoding': 'gzip', 'User-Agent': uaString }); if (!networkData) { context.report( resource, getMessage('couldNotBeFetchedGzip', context.language), { element, severity: Severity.error }); return; } const { rawResponse: uaRawResponse } = networkData; if (!isCompressedWithGzip(uaRawResponse) && shouldCheckIfCompressedWith.gzip) { context.report( resource, getMessage('compressedWithGzipAgent', context.language), { element, severity: Severity.error } ); return; } if (isNotCompressedWithZopfli(uaRawResponse) && !notCompressedWithZopfli && shouldCheckIfCompressedWith.zopfli) { context.report( resource, getMessage('compressedWithZopfliAgent', context.language), { element, severity: Severity.hint } ); } }; const responseIsCompressed = async (rawResponse: Buffer, contentEncodingHeaderValue: string | null): Promise<boolean> => { return isCompressedWithGzip(rawResponse) || await isCompressedWithBrotli(rawResponse) || /* * Other compression methods may be used, but there * is no way to check for all possible cases. So, if * this point is reached, consider 'content-encoding' * header as a possible indication of the response * being compressed. */ (!!contentEncodingHeaderValue && /* * Although `identity` should not be sent as a value * for `content-encoding`, if sent, for the scope of * this function, ignore it and consider no encoding * was specified. * * From (now kinda obsolete) * https://tools.ietf.org/html/rfc2616#page-24: * * " identity * * The default (identity) encoding; the use of no * transformation whatsoever. This content-coding * is used only in the Accept-Encoding header, and * SHOULD NOT be used in the Content-Encoding header. " * * See also: http://httpwg.org/specs/231.html#content.coding.registration */ (contentEncodingHeaderValue !== 'identity')); }; const checkForDisallowedCompressionMethods = async (resource: string, element: HTMLElement | null, response: Response) => { // See: https://www.iana.org/assignments/http-parameters/http-parameters.xml. const contentEncodingHeaderValue = normalizeHeaderValue(response.headers, 'content-encoding'); if (!contentEncodingHeaderValue) { return; } const encodings = contentEncodingHeaderValue.split(','); for (const encoding of encodings) { if (!['gzip', 'br'].includes(encoding)) { /* * `x-gzip` is deprecated but usually user agents * alias it to `gzip`, so if the content is actual * `gzip`, don't trigger an error here as the gzip * related check will show an error for the response * not being served with `content-encoding: gzip`. */ const safeRawResponse = asyncTry<Buffer>(response.body.rawResponse.bind(response.body)); const rawResponse: Buffer | null = await safeRawResponse(); if (!rawResponse) { context.report( resource, getMessage('couldNotBeFetched', context.language), { element, severity: Severity.error } ); return; } if (encoding === 'x-gzip' && isCompressedWithGzip(rawResponse)) { return; } // For anything else flag it as disallowed. context.report( resource, generateDisallowedCompressionMessage(encoding), { element, severity: Severity.warning } ); } } /* * Special cases: * * * SDCH (Shared Dictionary Compression over HTTP) * https://lists.w3.org/Archives/Public/ietf-http-wg/2008JulSep/att-0441/Shared_Dictionary_Compression_over_HTTP.pdf * Theoretically this should only happen if the user * agent advertises support for SDCH, but yet again, * server might be misconfigured. * * For SDCH, the first response will not contain anything * special regarding the `content-encoding` header, however, * it will contain the `get-dictionary` header. */ if (normalizeString(response.headers['get-dictionary'])) { context.report( resource, generateDisallowedCompressionMessage('sdch'), { element, severity: Severity.warning } ); } }; const checkUncompressed = async (resource: string, element: HTMLElement | null) => { /* * From: http://httpwg.org/specs/rfc7231.html#header.accept-encoding * * " An "identity" token is used as a synonym for * "no encoding" in order to communicate when no * encoding is preferred. * * ... * * If no Accept-Encoding field is in the request, * any content-coding is considered acceptable by * the user agent. " */ const networkData = await getNetworkData(resource, { 'Accept-Encoding': 'identity' }); if (!networkData) { context.report( resource, getMessage('couldNotBeFetchedUncompressed', context.language), { element, severity: Severity.error } ); return; } const { contentEncodingHeaderValue, rawResponse } = networkData; if (await responseIsCompressed(rawResponse, contentEncodingHeaderValue)) { context.report( resource, getMessage('shouldNotBeCompressedWithIdentity', context.language), { element, severity: Severity.warning } ); } if (contentEncodingHeaderValue) { context.report( resource, getMessage('shouldNotIncludeWithIdentity', context.language), { element, severity: Severity.warning } ); } }; const isCompressibleAccordingToMediaType = (mediaType: string): boolean => { if (!mediaType) { return false; } const OTHER_COMMON_MEDIA_TYPES_THAT_SHOULD_BE_COMPRESSED = [ 'application/rtf', 'application/wasm', 'font/collection', 'font/eot', 'font/otf', 'font/sfnt', 'font/ttf', 'image/bmp', 'image/vnd.microsoft.icon', 'image/x-icon', 'x-shader/x-fragment', 'x-shader/x-vertex' ]; /* * Check if the media type is one of the common * ones for which it is known the response should * be compressed. */ if (isTextMediaType(mediaType) || OTHER_COMMON_MEDIA_TYPES_THAT_SHOULD_BE_COMPRESSED.includes(mediaType)) { return true; } return false; }; const isSpecialCase = async (resource: string, element: HTMLElement | null, response: Response): Promise<boolean> => { /* * Check for special cases: * * * Files that are by default compressed with gzip. * * SVGZ files are by default compressed with gzip, so * by not sending them with the `Content-Encoding: gzip` * header, browsers will not be able to display them * correctly. */ const safeRawResponse = asyncTry<Buffer>(response.body.rawResponse.bind(response.body)); const rawResponse: Buffer | null = await safeRawResponse(); if (!rawResponse) { context.report( resource, getMessage('couldNotBeFetched', context.language), { element, severity: Severity.error } ); return false; } if ((response.mediaType === 'image/svg+xml' || getFileExtension(resource) === 'svgz') && isCompressedWithGzip(rawResponse)) { const headerValue = normalizeHeaderValue(response.headers, 'content-encoding'); if (headerValue !== 'gzip') { context.report( resource, generateContentEncodingMessage('gzip'), { codeLanguage: 'http', codeSnippet: `Content-Encoding: ${headerValue}`, severity: Severity.error } ); } return true; } return false; }; const validate = async ({ element, resource, response }: FetchEnd, eventName: string) => { const shouldCheckIfCompressedWith: CompressionCheckOptions = eventName === 'fetch::end::html' ? htmlOptions : resourceOptions; /* * We shouldn't validate error responses, and 204 (response with no body). * Also some sites return body with 204 status code and that breaks `request`: * https://github.com/request/request/issues/2669 */ if (response.statusCode !== 200) { return; } // It doesn't make sense for things that are not served over http(s) if (!isRegularProtocol(resource)) { return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* * Check if this is a special case, and if it is, do the * specific checks, but ignore all the checks that follow. */ if (await isSpecialCase(resource, element, response)) { return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // If the resource should not be compressed: if (!isCompressibleAccordingToMediaType(response.mediaType)) { const safeRawResponse = asyncTry<Buffer>(response.body.rawResponse.bind(response.body)); const rawResponse: Buffer | null = await safeRawResponse(); if (!rawResponse) { context.report( resource, getMessage('couldNotBeFetched', context.language), { element, severity: Severity.error } ); return; } const contentEncodingHeaderValue = normalizeHeaderValue(response.headers, 'content-encoding'); // * Check if the resource is actually compressed. if (await responseIsCompressed(rawResponse, contentEncodingHeaderValue)) { context.report( resource, getMessage('shouldNotBeCompressed', context.language), { element, severity: Severity.warning } ); } // * Check if resource is sent with the `Content-Encoding` header. if (contentEncodingHeaderValue) { context.report( resource, getMessage('shouldNotIncludeContentEncoding', context.language), { codeLanguage: 'http', codeSnippet: `Content-Encoding: ${contentEncodingHeaderValue}`, severity: Severity.warning } ); } return; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* * If the resource should be compressed: * * * Check if the resource is sent compressed with an * deprecated or not recommended compression method. */ await checkForDisallowedCompressionMethods(resource, element, response); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* * * Check if it's actually compressed and served in * the correct/required compressed format. * * Note: Checking if servers respect the qvalue * is beyond of the scope for the time being, * so the followings won't check that. */ await checkUncompressed(resource, element); if (shouldCheckIfCompressedWith.gzip || shouldCheckIfCompressedWith.zopfli) { await checkGzipZopfli(resource, element, shouldCheckIfCompressedWith); } if (shouldCheckIfCompressedWith.brotli) { await checkBrotli(resource, element, shouldCheckIfCompressedWith); } }; context.on('fetch::end::*', validate); } }
the_stack
import ENGLISH, { Language } from './i18n' import RRule from '../index' import { Options } from '../types' import { WeekdayStr } from '../weekday' // ============================================================================= // Parser // ============================================================================= class Parser { private readonly rules: { [k: string]: RegExp } public text: string public symbol: string | null public value: RegExpExecArray | null private done = true constructor (rules: { [k: string]: RegExp }) { this.rules = rules } start (text: string) { this.text = text this.done = false return this.nextSymbol() } isDone () { return this.done && this.symbol === null } nextSymbol () { let best: RegExpExecArray | null let bestSymbol: string const p = this this.symbol = null this.value = null do { if (this.done) return false let rule: RegExp best = null for (let name in this.rules) { rule = this.rules[name] const match = rule.exec(p.text) if (match) { if (best === null || match[0].length > best[0].length) { best = match bestSymbol = name } } } if (best != null) { this.text = this.text.substr(best[0].length) if (this.text === '') this.done = true } if (best == null) { this.done = true this.symbol = null this.value = null return } // @ts-ignore } while (bestSymbol === 'SKIP') // @ts-ignore this.symbol = bestSymbol this.value = best return true } accept (name: string) { if (this.symbol === name) { if (this.value) { const v = this.value this.nextSymbol() return v } this.nextSymbol() return true } return false } acceptNumber () { return this.accept('number') as RegExpExecArray } expect (name: string) { if (this.accept(name)) return true throw new Error('expected ' + name + ' but found ' + this.symbol) } } export default function parseText (text: string, language: Language = ENGLISH) { const options: Partial<Options> = {} const ttr = new Parser(language.tokens) if (!ttr.start(text)) return null S() return options function S () { // every [n] ttr.expect('every') let n = ttr.acceptNumber() if (n) options.interval = parseInt(n[0], 10) if (ttr.isDone()) throw new Error('Unexpected end') switch (ttr.symbol) { case 'day(s)': options.freq = RRule.DAILY if (ttr.nextSymbol()) { AT() F() } break // FIXME Note: every 2 weekdays != every two weeks on weekdays. // DAILY on weekdays is not a valid rule case 'weekday(s)': options.freq = RRule.WEEKLY options.byweekday = [ RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR ] ttr.nextSymbol() F() break case 'week(s)': options.freq = RRule.WEEKLY if (ttr.nextSymbol()) { ON() F() } break case 'hour(s)': options.freq = RRule.HOURLY if (ttr.nextSymbol()) { ON() F() } break case 'minute(s)': options.freq = RRule.MINUTELY if (ttr.nextSymbol()) { ON() F() } break case 'month(s)': options.freq = RRule.MONTHLY if (ttr.nextSymbol()) { ON() F() } break case 'year(s)': options.freq = RRule.YEARLY if (ttr.nextSymbol()) { ON() F() } break case 'monday': case 'tuesday': case 'wednesday': case 'thursday': case 'friday': case 'saturday': case 'sunday': options.freq = RRule.WEEKLY const key: WeekdayStr = ttr.symbol.substr(0, 2).toUpperCase() as WeekdayStr options.byweekday = [RRule[key]] if (!ttr.nextSymbol()) return // TODO check for duplicates while (ttr.accept('comma')) { if (ttr.isDone()) throw new Error('Unexpected end') let wkd = decodeWKD() as keyof typeof RRule if (!wkd) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected weekday') } // @ts-ignore options.byweekday.push(RRule[wkd]) ttr.nextSymbol() } MDAYs() F() break case 'january': case 'february': case 'march': case 'april': case 'may': case 'june': case 'july': case 'august': case 'september': case 'october': case 'november': case 'december': options.freq = RRule.YEARLY options.bymonth = [decodeM() as number] if (!ttr.nextSymbol()) return // TODO check for duplicates while (ttr.accept('comma')) { if (ttr.isDone()) throw new Error('Unexpected end') let m = decodeM() if (!m) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected month') } options.bymonth.push(m) ttr.nextSymbol() } ON() F() break default: throw new Error('Unknown symbol') } } function ON () { const on = ttr.accept('on') const the = ttr.accept('the') if (!(on || the)) return do { let nth = decodeNTH() let wkd = decodeWKD() let m = decodeM() // nth <weekday> | <weekday> if (nth) { // ttr.nextSymbol() if (wkd) { ttr.nextSymbol() if (!options.byweekday) options.byweekday = [] // @ts-ignore options.byweekday.push(RRule[wkd].nth(nth)) } else { if (!options.bymonthday) options.bymonthday = [] // @ts-ignore options.bymonthday.push(nth) ttr.accept('day(s)') } // <weekday> } else if (wkd) { ttr.nextSymbol() if (!options.byweekday) options.byweekday = [] // @ts-ignore options.byweekday.push(RRule[wkd]) } else if (ttr.symbol === 'weekday(s)') { ttr.nextSymbol() if (!options.byweekday) { options.byweekday = [ RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR ] } } else if (ttr.symbol === 'week(s)') { ttr.nextSymbol() let n = ttr.acceptNumber() if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected week number') } options.byweekno = [parseInt(n[0], 10)] while (ttr.accept('comma')) { n = ttr.acceptNumber() if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected monthday') } options.byweekno.push(parseInt(n[0], 10)) } } else if (m) { ttr.nextSymbol() if (!options.bymonth) options.bymonth = [] // @ts-ignore options.bymonth.push(m) } else { return } } while (ttr.accept('comma') || ttr.accept('the') || ttr.accept('on')) } function AT () { const at = ttr.accept('at') if (!at) return do { let n = ttr.acceptNumber() if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected hour') } options.byhour = [parseInt(n[0], 10)] while (ttr.accept('comma')) { n = ttr.acceptNumber() if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected hour') } options.byhour.push(parseInt(n[0], 10)) } } while (ttr.accept('comma') || ttr.accept('at')) } function decodeM () { switch (ttr.symbol) { case 'january': return 1 case 'february': return 2 case 'march': return 3 case 'april': return 4 case 'may': return 5 case 'june': return 6 case 'july': return 7 case 'august': return 8 case 'september': return 9 case 'october': return 10 case 'november': return 11 case 'december': return 12 default: return false } } function decodeWKD () { switch (ttr.symbol) { case 'monday': case 'tuesday': case 'wednesday': case 'thursday': case 'friday': case 'saturday': case 'sunday': return ttr.symbol.substr(0, 2).toUpperCase() default: return false } } function decodeNTH () { switch (ttr.symbol) { case 'last': ttr.nextSymbol() return -1 case 'first': ttr.nextSymbol() return 1 case 'second': ttr.nextSymbol() return ttr.accept('last') ? -2 : 2 case 'third': ttr.nextSymbol() return ttr.accept('last') ? -3 : 3 case 'nth': const v = parseInt(ttr.value![1], 10) if (v < -366 || v > 366) throw new Error('Nth out of range: ' + v) ttr.nextSymbol() return ttr.accept('last') ? -v : v default: return false } } function MDAYs () { ttr.accept('on') ttr.accept('the') let nth = decodeNTH() if (!nth) return options.bymonthday = [nth] ttr.nextSymbol() while (ttr.accept('comma')) { nth = decodeNTH() if (!nth) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected monthday') } options.bymonthday.push(nth) ttr.nextSymbol() } } function F () { if (ttr.symbol === 'until') { const date = Date.parse(ttr.text) if (!date) throw new Error('Cannot parse until date:' + ttr.text) options.until = new Date(date) } else if (ttr.accept('for')) { options.count = parseInt(ttr.value![0], 10) ttr.expect('number') // ttr.expect('times') } } }
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import React, { Component, ReactElement } from 'react'; import { EuiButton, EuiCopy, EuiFlexGroup, EuiSpacer, EuiFlexItem, EuiForm, EuiFormRow, EuiIconTip, EuiLoadingSpinner, EuiRadioGroup, EuiSwitch, EuiSwitchEvent, } from '@elastic/eui'; import { format as formatUrl, parse as parseUrl } from 'url'; import { FormattedMessage, I18nProvider } from '@osd/i18n/react'; import { HttpStart } from 'opensearch-dashboards/public'; import { i18n } from '@osd/i18n'; import { shortenUrl } from '../lib/url_shortener'; import { UrlParamExtension } from '../types'; interface Props { allowShortUrl: boolean; isEmbedded?: boolean; objectId?: string; objectType: string; shareableUrl?: string; basePath: string; post: HttpStart['post']; urlParamExtensions?: UrlParamExtension[]; } export enum ExportUrlAsType { EXPORT_URL_AS_SAVED_OBJECT = 'savedObject', EXPORT_URL_AS_SNAPSHOT = 'snapshot', } interface UrlParams { [extensionName: string]: { [queryParam: string]: boolean; }; } interface State { exportUrlAs: ExportUrlAsType; useShortUrl: boolean; isCreatingShortUrl: boolean; url?: string; shortUrlErrorMsg?: string; urlParams?: UrlParams; } export class UrlPanelContent extends Component<Props, State> { private mounted?: boolean; private shortUrlCache?: string; constructor(props: Props) { super(props); this.shortUrlCache = undefined; this.state = { exportUrlAs: ExportUrlAsType.EXPORT_URL_AS_SNAPSHOT, useShortUrl: false, isCreatingShortUrl: false, url: '', }; } public componentWillUnmount() { window.removeEventListener('hashchange', this.resetUrl); this.mounted = false; } public componentDidMount() { this.mounted = true; this.setUrl(); window.addEventListener('hashchange', this.resetUrl, false); } public render() { return ( <I18nProvider> <EuiForm className="osdShareContextMenu__finalPanel" data-test-subj="shareUrlForm"> {this.renderExportAsRadioGroup()} {this.renderUrlParamExtensions()} {this.renderShortUrlSwitch()} <EuiSpacer size="m" /> <EuiCopy textToCopy={this.state.url || ''} anchorClassName="eui-displayBlock"> {(copy: () => void) => ( <EuiButton fill fullWidth onClick={copy} disabled={this.state.isCreatingShortUrl || this.state.url === ''} data-share-url={this.state.url} data-test-subj="copyShareUrlButton" size="s" > {this.props.isEmbedded ? ( <FormattedMessage id="share.urlPanel.copyIframeCodeButtonLabel" defaultMessage="Copy iFrame code" /> ) : ( <FormattedMessage id="share.urlPanel.copyLinkButtonLabel" defaultMessage="Copy link" /> )} </EuiButton> )} </EuiCopy> </EuiForm> </I18nProvider> ); } private isNotSaved = () => { return this.props.objectId === undefined || this.props.objectId === ''; }; private resetUrl = () => { if (this.mounted) { this.shortUrlCache = undefined; this.setState( { useShortUrl: false, }, this.setUrl ); } }; private updateUrlParams = (url: string) => { const embedUrl = this.props.isEmbedded ? this.makeUrlEmbeddable(url) : url; const extendUrl = this.state.urlParams ? this.getUrlParamExtensions(embedUrl) : embedUrl; return extendUrl; }; private getSavedObjectUrl = () => { if (this.isNotSaved()) { return; } const url = this.getSnapshotUrl(); const parsedUrl = parseUrl(url); if (!parsedUrl || !parsedUrl.hash) { return; } // Get the application route, after the hash, and remove the #. const parsedAppUrl = parseUrl(parsedUrl.hash.slice(1), true); const formattedUrl = formatUrl({ protocol: parsedUrl.protocol, auth: parsedUrl.auth, host: parsedUrl.host, pathname: parsedUrl.pathname, hash: formatUrl({ pathname: parsedAppUrl.pathname, query: { // Add global state to the URL so that the iframe doesn't just show the time range // default. _g: parsedAppUrl.query._g, }, }), }); return this.updateUrlParams(formattedUrl); }; private getSnapshotUrl = () => { const url = this.props.shareableUrl || window.location.href; return this.updateUrlParams(url); }; private makeUrlEmbeddable = (url: string): string => { const embedParam = '?embed=true'; const urlHasQueryString = url.indexOf('?') !== -1; if (urlHasQueryString) { return url.replace('?', `${embedParam}&`); } return `${url}${embedParam}`; }; private getUrlParamExtensions = (url: string): string => { const { urlParams } = this.state; return urlParams ? Object.keys(urlParams).reduce((urlAccumulator, key) => { const urlParam = urlParams[key]; return urlParam ? Object.keys(urlParam).reduce((queryAccumulator, queryParam) => { const isQueryParamEnabled = urlParam[queryParam]; return isQueryParamEnabled ? queryAccumulator + `&${queryParam}=true` : queryAccumulator; }, urlAccumulator) : urlAccumulator; }, url) : url; }; private makeIframeTag = (url?: string) => { if (!url) { return; } return `<iframe src="${url}" height="600" width="800"></iframe>`; }; private setUrl = () => { let url; if (this.state.exportUrlAs === ExportUrlAsType.EXPORT_URL_AS_SAVED_OBJECT) { url = this.getSavedObjectUrl(); } else if (this.state.useShortUrl) { url = this.shortUrlCache; } else { url = this.getSnapshotUrl(); } if (this.props.isEmbedded) { url = this.makeIframeTag(url); } this.setState({ url }); }; private handleExportUrlAs = (optionId: string) => { this.setState( { exportUrlAs: optionId as ExportUrlAsType, }, this.setUrl ); }; private handleShortUrlChange = async (evt: EuiSwitchEvent) => { const isChecked = evt.target.checked; if (!isChecked || this.shortUrlCache !== undefined) { this.setState({ useShortUrl: isChecked }, this.setUrl); return; } // "Use short URL" is checked but shortUrl has not been generated yet so one needs to be created. this.createShortUrl(); }; private createShortUrl = async () => { this.setState({ isCreatingShortUrl: true, shortUrlErrorMsg: undefined, }); try { const shortUrl = await shortenUrl(this.getSnapshotUrl(), { basePath: this.props.basePath, post: this.props.post, }); if (this.mounted) { this.shortUrlCache = shortUrl; this.setState( { isCreatingShortUrl: false, useShortUrl: true, }, this.setUrl ); } } catch (fetchError) { if (this.mounted) { this.shortUrlCache = undefined; this.setState( { useShortUrl: false, isCreatingShortUrl: false, shortUrlErrorMsg: i18n.translate('share.urlPanel.unableCreateShortUrlErrorMessage', { defaultMessage: 'Unable to create short URL. Error: {errorMessage}', values: { errorMessage: fetchError.message, }, }), }, this.setUrl ); } } }; private renderExportUrlAsOptions = () => { return [ { id: ExportUrlAsType.EXPORT_URL_AS_SNAPSHOT, label: this.renderWithIconTip( <FormattedMessage id="share.urlPanel.snapshotLabel" defaultMessage="Snapshot" />, <FormattedMessage id="share.urlPanel.snapshotDescription" defaultMessage="Snapshot URLs encode the current state of the {objectType} in the URL itself. Edits to the saved {objectType} won't be visible via this URL." values={{ objectType: this.props.objectType }} /> ), ['data-test-subj']: 'exportAsSnapshot', }, { id: ExportUrlAsType.EXPORT_URL_AS_SAVED_OBJECT, disabled: this.isNotSaved(), label: this.renderWithIconTip( <FormattedMessage id="share.urlPanel.savedObjectLabel" defaultMessage="Saved object" />, <FormattedMessage id="share.urlPanel.savedObjectDescription" defaultMessage="You can share this URL with people to let them load the most recent saved version of this {objectType}." values={{ objectType: this.props.objectType }} /> ), ['data-test-subj']: 'exportAsSavedObject', }, ]; }; private renderWithIconTip = (child: React.ReactNode, tipContent: React.ReactNode) => { return ( <EuiFlexGroup gutterSize="none" responsive={false}> <EuiFlexItem grow={false}>{child}</EuiFlexItem> <EuiFlexItem grow={false}> <EuiIconTip content={tipContent} position="bottom" /> </EuiFlexItem> </EuiFlexGroup> ); }; private renderExportAsRadioGroup = () => { const generateLinkAsHelp = this.isNotSaved() ? ( <FormattedMessage id="share.urlPanel.canNotShareAsSavedObjectHelpText" defaultMessage="Can't share as saved object until the {objectType} has been saved." values={{ objectType: this.props.objectType }} /> ) : undefined; return ( <EuiFormRow label={ <FormattedMessage id="share.urlPanel.generateLinkAsLabel" defaultMessage="Generate the link as" /> } helpText={generateLinkAsHelp} > <EuiRadioGroup options={this.renderExportUrlAsOptions()} idSelected={this.state.exportUrlAs} onChange={this.handleExportUrlAs} /> </EuiFormRow> ); }; private renderShortUrlSwitch = () => { if ( this.state.exportUrlAs === ExportUrlAsType.EXPORT_URL_AS_SAVED_OBJECT || !this.props.allowShortUrl ) { return; } const shortUrlLabel = ( <FormattedMessage id="share.urlPanel.shortUrlLabel" defaultMessage="Short URL" /> ); const switchLabel = this.state.isCreatingShortUrl ? ( <span> <EuiLoadingSpinner size="s" /> {shortUrlLabel} </span> ) : ( shortUrlLabel ); const switchComponent = ( <EuiSwitch label={switchLabel} checked={this.state.useShortUrl} onChange={this.handleShortUrlChange} data-test-subj="useShortUrl" /> ); const tipContent = ( <FormattedMessage id="share.urlPanel.shortUrlHelpText" defaultMessage="We recommend sharing shortened snapshot URLs for maximum compatibility. Internet Explorer has URL length restrictions, and some wiki and markup parsers don't do well with the full-length version of the snapshot URL, but the short URL should work great." /> ); return ( <EuiFormRow helpText={this.state.shortUrlErrorMsg} data-test-subj="createShortUrl"> {this.renderWithIconTip(switchComponent, tipContent)} </EuiFormRow> ); }; private renderUrlParamExtensions = (): ReactElement | void => { if (!this.props.urlParamExtensions) { return; } const setParamValue = (paramName: string) => ( values: { [queryParam: string]: boolean } = {} ): void => { const stateUpdate = { urlParams: { ...this.state.urlParams, [paramName]: { ...values, }, }, }; this.setState(stateUpdate, this.state.useShortUrl ? this.createShortUrl : this.setUrl); }; return ( <React.Fragment> {this.props.urlParamExtensions.map(({ paramName, component: UrlParamComponent }) => ( <EuiFormRow key={paramName}> <UrlParamComponent setParamValue={setParamValue(paramName)} /> </EuiFormRow> ))} </React.Fragment> ); }; }
the_stack
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ImageWithRegionsEditorComponent } from './image-with-regions-editor.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ContextService } from 'services/context.service'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { ImageWithRegionsResetConfirmationModalComponent } from './image-with-regions-reset-confirmation.component'; import { AppConstants } from 'app.constants'; describe('ImageWithRegionsEditorComponent', () => { let component: ImageWithRegionsEditorComponent; let ngbModal: NgbModal; let fixture: ComponentFixture<ImageWithRegionsEditorComponent>; let contextService: ContextService; class MockImageObject { source = null; onload!: () => string; width = 0; height = 0; constructor(_width: 0, _height: 0) { this.width = _width; this.height = _height; this.onload = () => { return 'Fake onload executed'; }; } set src(url: string) { this.onload(); } } beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [ImageWithRegionsEditorComponent], providers: [ContextService], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { ngbModal = TestBed.inject(NgbModal); contextService = TestBed.inject(ContextService); fixture = TestBed.createComponent(ImageWithRegionsEditorComponent); component = fixture.componentInstance; component.value = { imagePath: 'img_20210627_214959_mwljsqraka_height_691_width_392.svg', labeledRegions: [ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ] }; // This throws "Argument of type 'mockImageObject' is not assignable to // parameter of type 'HTMLImageElement'.". We need to suppress this // error because 'HTMLImageElement' has around 250 more properties. // We have only defined the properties we need in 'mockImageObject'. // @ts-expect-error spyOn(window, 'Image').and.returnValue(new MockImageObject(490, 864)); }); it('should initialize component when interaction editor is opened.', () => { spyOn(component, 'initializeEditor').and.callThrough(); spyOn(component, 'imageValueChanged').and.callThrough(); spyOn(contextService, 'getEntityType').and.returnValue( AppConstants.ENTITY_TYPE.EXPLORATION); spyOn(contextService, 'getExplorationId').and.returnValue('exploration_id'); spyOn(component.valueChanged, 'emit'); component.ngOnInit(); expect(component.alwaysEditable).toBe(true); expect(component.SCHEMA).toEqual({ type: 'custom', obj_type: 'Filepath' }); // Testing values initialised in initializeEditor function. expect(component.initializeEditor).toHaveBeenCalled(); expect(component.mouseX).toBe(0); expect(component.mouseY).toBe(0); expect(component.originalMouseX).toBe(0); expect(component.originalMouseY).toBe(0); expect(component.originalRectArea).toEqual({ x: 0, y: 0, width: 0, height: 0 }); expect(component.rectX).toBe(0); expect(component.rectY).toBe(0); expect(component.rectWidth).toBe(0); expect(component.rectHeight).toBe(0); expect(component.userIsCurrentlyDrawing).toBe(false); expect(component.userIsCurrentlyDragging).toBe(false); expect(component.userIsCurrentlyResizing).toBe(false); expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); expect(component.yDirectionToggled).toBe(false); expect(component.xDirectionToggled).toBe(false); expect(component.movedOutOfRegion).toBe(false); expect(component.resizableBorderWidthPx).toBe(10); expect(component.hoveredRegion).toBeNull(); expect(component.selectedRegion).toBeNull(); expect(component.errorText).toBe(''); // Testing values initalised in the imageValueChanged function. expect(component.imageValueChanged).toHaveBeenCalled(); expect(component.originalImageWidth).toBe(490); expect(component.originalImageHeight).toBe(864); expect(component.valueChanged.emit).toHaveBeenCalledWith(component.value); }); it('should initialize component when interaction editor is opened with a' + ' custom entity context', () => { spyOn(component, 'initializeEditor').and.callThrough(); spyOn(component, 'imageValueChanged').and.callThrough(); spyOn(contextService, 'getEntityType').and.returnValue( AppConstants.IMAGE_CONTEXT.QUESTION_SUGGESTIONS); spyOn(contextService, 'getEntityId').and.returnValue('skill_1'); spyOn(component.valueChanged, 'emit'); component.ngOnInit(); expect(component.alwaysEditable).toBe(true); expect(component.SCHEMA).toEqual({ type: 'custom', obj_type: 'Filepath' }); // Testing values initialised in initializeEditor function. expect(component.initializeEditor).toHaveBeenCalled(); expect(component.mouseX).toBe(0); expect(component.mouseY).toBe(0); expect(component.originalMouseX).toBe(0); expect(component.originalMouseY).toBe(0); expect(component.originalRectArea).toEqual({ x: 0, y: 0, width: 0, height: 0 }); expect(component.rectX).toBe(0); expect(component.rectY).toBe(0); expect(component.rectWidth).toBe(0); expect(component.rectHeight).toBe(0); expect(component.userIsCurrentlyDrawing).toBe(false); expect(component.userIsCurrentlyDragging).toBe(false); expect(component.userIsCurrentlyResizing).toBe(false); expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); expect(component.yDirectionToggled).toBe(false); expect(component.xDirectionToggled).toBe(false); expect(component.movedOutOfRegion).toBe(false); expect(component.resizableBorderWidthPx).toBe(10); expect(component.hoveredRegion).toBeNull(); expect(component.selectedRegion).toBeNull(); expect(component.errorText).toBe(''); // Testing values initalised in the imageValueChanged function. expect(component.imageValueChanged).toHaveBeenCalled(); expect(component.originalImageWidth).toBe(490); expect(component.originalImageHeight).toBe(864); expect(component.valueChanged.emit).toHaveBeenCalledWith(component.value); }); // For the following tests Pre-Checks cannot be added because a state change // does not occur within these functions. They just return css styling for // various components of the region. it('should return selected region css styling for the rectangle' + ' when a region is selected', () => { component.selectedRegion = 0; expect(component.getRegionStyle(0)) .toBe('fill: #00f; opacity: 0.5; stroke: #00d'); }); it('should return default region css styling for the rectangle' + ' when a region is not selected', () => { component.selectedRegion = 0; expect(component.getRegionStyle(1)) .toBe('fill: white; opacity: 0.5; stroke: #ddd'); }); it('should return selected region trash icon css styling' + ' when a region is selected', () => { component.selectedRegion = 0; expect(component.getRegionTrashStyle(0)) .toBe('fill: #eee; opacity: 0.7'); }); it('should return default trash icon css styling for the trash icon' + ' when a region is not selected', () => { component.selectedRegion = 0; expect(component.getRegionTrashStyle(1)) .toBe('fill: #333; opacity: 0.7'); }); it('should return region label css styling for a selected region' + ' when a region is selected', () => { component.selectedRegion = 0; expect(component.getRegionLabelStyle(0)) .toBe( 'font-size: 14px; pointer-events: none; fill: #eee; visibility: hidden;' ); }); it('should return default label css styling for other regions' + ' when a region is not selected', () => { component.selectedRegion = 0; expect(component.getRegionLabelStyle(1)) .toBe( 'font-size: 14px; pointer-events: none; fill: ' + '#333; visibility: visible;' ); }); it('should return region label text input css styling for a selected region' + ' when a region is selected', () => { spyOn(component, 'getRegionStyle').and.callThrough(); spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.selectedRegion = 0; component.originalImageWidth = 490; component.originalImageHeight = 864; expect(component.getRegionLabelEditorStyle()) .toBe( 'left: 119.80300480573808px; top: 96.47803081918576px;' + ' width: 145.16998004770895px;' ); }); it('should return default label css styling for other regions' + ' when no region is selected', () => { component.selectedRegion = null; expect(component.getRegionLabelEditorStyle()).toBe('display: none'); }); it('should set region label when user enter a label for a region', () => { component.selectedRegion = null; component.selectedRegion = 0; component.errorText = ''; expect(component.value.labeledRegions[0].label).toBe('Region1'); component.regionLabelSetter('new region 1'); expect(component.value.labeledRegions[0].label).toBe('new region 1'); // The error text value should not change since there is no error present. expect(component.errorText).toBe(''); }); it('should warn if user when user enters a duplicate label', () => { component.selectedRegion = null; component.selectedRegion = 0; component.errorText = ''; expect(component.value.labeledRegions[0].label).toBe('Region1'); component.regionLabelSetter('Region2'); expect(component.value.labeledRegions[0].label).toBe('Region2'); expect(component.errorText).toBe( 'Warning: Label "Region2" already ' + 'exists! Please use a different label.'); }); it('should get dimenions of region when user is drawing the region', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(500); spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(400); let evt = new MouseEvent('Mousemove'); component.userIsCurrentlyDrawing = true; component.originalMouseX = 200; component.originalMouseY = 200; component.onSvgMouseMove(evt); expect(component.mouseX).toBe(22.881927490234375); expect(component.mouseY).toBe(228.8367919921875); expect(component.rectX).toBe(22.881927490234375); expect(component.rectY).toBe(200); expect(component.rectWidth).toBe(177.11807250976562); expect(component.rectHeight).toBe(28.8367919921875); }); it('should get new location of region when user is dragging the' + ' region diagonally down', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(700); spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(600); let evt = new MouseEvent('Mousemove'); component.userIsCurrentlyDragging = true; component.originalMouseX = 500; component.originalMouseY = 500; component.originalImageWidth = 968; component.originalImageHeight = 1707; component.selectedRegion = 0; component.originalRectArea = { x: 113.80300480573808, y: 70.47803081918576, width: 157.16998004770895, height: 209.09648961070076 }; spyOn(component, 'getImageWidth').and.callThrough(); spyOn(component, 'getImageHeight').and.callThrough(); expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] }); component.onSvgMouseMove(evt); expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0, 0 ], [ 0.21361468893287125, 0.16115734093948267 ] ] }); }); it('should get new location of region when user is dragging the' + ' region diagonally up', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(2000); spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(1707); let evt = new MouseEvent('Mousemove'); component.userIsCurrentlyDragging = true; component.originalMouseX = 500; component.originalMouseY = 500; component.originalImageWidth = 968; component.originalImageHeight = 1707; component.selectedRegion = 0; component.originalRectArea = { x: 113.80300480573808, y: 70.47803081918576, width: 157.16998004770895, height: 209.09648961070076 }; spyOn(component, 'getImageWidth').and.callThrough(); spyOn(component, 'getImageHeight').and.callThrough(); expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] }); component.onSvgMouseMove(evt); expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.7863853110671288, 0.8388426590605174 ], [ 1, 1 ] ] }); }); it('should increase the hight (top) and width (left) of the region ' + 'when user is resizing the region', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(600); spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(400); let evt = new MouseEvent('Mousemove'); component.userIsCurrentlyDrawing = false; component.userIsCurrentlyDragging = false; component.userIsCurrentlyResizing = true; component.originalMouseX = 200; component.originalMouseY = 200; component.selectedRegion = 0; component.originalImageWidth = 968; component.originalImageHeight = 1707; component.originalRectArea = { x: 113.80300480573808, y: 70.47803081918576, width: 157.16998004770895, height: 209.09648961070076 }; component.yDirectionToggled = true; component.xDirectionToggled = true; component.yDirection = 1; component.xDirection = 1; expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] }); component.onSvgMouseMove(evt); expect(component.yDirectionToggled).toBe(false); expect(component.xDirectionToggled).toBe(false); expect(component.value.labeledRegions[0].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.04985965130585909, 0.0765451050371804 ], [ 0.36828795073404025, 0.21547700963701794 ] ] }); }); it('should increase the hight (bottom) and width (right) of the region ' + 'when user is resizing the region', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(600); spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(200); let evt = new MouseEvent('Mousemove'); component.userIsCurrentlyDrawing = false; component.userIsCurrentlyDragging = false; component.userIsCurrentlyResizing = true; component.originalMouseX = 500; component.originalMouseY = 500; component.selectedRegion = 1; component.originalImageWidth = 968; component.originalImageHeight = 1707; component.originalRectArea = { x: 113.80300480573808, y: 70.47803081918576, width: 157.16998004770895, height: 209.09648961070076 }; component.yDirectionToggled = false; component.xDirectionToggled = false; component.yDirection = -1; component.xDirection = -1; expect(component.value.labeledRegions[1].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] }); component.onSvgMouseMove(evt); expect(component.yDirectionToggled).toBe(true); expect(component.xDirectionToggled).toBe(true); expect(component.value.labeledRegions[1].region).toEqual({ regionType: 'Rectangle', area: [ [ 0.16701271265880457, 0.022225436339645178 ], [ 0.46595111895241487, 0.22420862393043944 ] ] }); }); it('should start drawing region when user clicks mouse down', () => { let evt = document.createEvent('MouseEvent'); evt.initMouseEvent( 'click', true, true, window, 1, 800, 600, 500, 400, false, false, false, false, 0, null ); spyOn(Event.prototype, 'preventDefault'); component.mouseX = 500; component.mouseY = 400; component.hoveredRegion = null; component.rectHeight = 10; component.rectWidth = 10; component.originalMouseX = 0; component.originalMouseY = 0; component.userIsCurrentlyDragging = false; component.onSvgMouseDown(evt); expect(Event.prototype.preventDefault).toHaveBeenCalled(); expect(component.rectWidth).toBe(0); expect(component.rectHeight).toBe(0); expect(component.originalMouseX).toBe(500); expect(component.originalMouseY).toBe(400); expect(component.userIsCurrentlyDrawing).toBe(true); }); it('should reset variables when user\'s mouse moves out of region', () => { component.hoveredRegion = null; component.selectedRegion = 1; component.userIsCurrentlyDragging = true; component.userIsCurrentlyResizing = true; component.movedOutOfRegion = true; component.xDirection = 1; component.yDirection = 1; spyOn(contextService, 'getEntityType').and.returnValue( AppConstants.ENTITY_TYPE.EXPLORATION); spyOn(contextService, 'getExplorationId').and.returnValue('exploration_id'); component.onSvgMouseUp(); expect(component.selectedRegion).toBe(null); expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); expect(component.userIsCurrentlyDragging).toBe(false); expect(component.userIsCurrentlyResizing).toBe(false); expect(component.movedOutOfRegion).toBe(false); }); it('should insert region when user releases mouse button', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.xDirectionToggled = true; component.yDirectionToggled = true; component.userIsCurrentlyDrawing = true; component.xDirection = 0; component.yDirection = 0; component.rectX = 250; component.rectY = 350; component.rectWidth = 260; component.rectHeight = 360; component.originalImageWidth = 968; component.originalImageHeight = 1707; expect(component.value.labeledRegions).toEqual([ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ]); component.onSvgMouseUp(); expect(component.yDirection).toBe(1); expect(component.xDirection).toBe(1); expect(component.value.labeledRegions).toEqual([ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } }, { label: 'Region3', region: { regionType: 'Rectangle', area: [ [ 0.33978290394264304, 0.2697561754089455 ], [ 0.6931571240429918, 0.5472196701152894 ] ] } } ]); expect(component.userIsCurrentlyDrawing).toBe(false); expect(component.yDirectionToggled).toBe(false); expect(component.xDirectionToggled).toBe(false); }); it('should check if mouse is over region when user moves mouse over' + ' a region', () => { component.hoveredRegion = null; component.movedOutOfRegion = true; component.onMouseoverRegion(1); expect(component.hoveredRegion).toBe(1); expect(component.movedOutOfRegion).toBe(false); }); it('should reset values if user is not hovering over a region' + ' and is not resizing', () => { component.hoveredRegion = 1; component.userIsCurrentlyResizing = false; component.xDirection = 1; component.yDirection = 1; component.movedOutOfRegion = false; component.onMouseoutRegion(1); expect(component.hoveredRegion).toBeNull(); expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); expect(component.movedOutOfRegion).toBe(true); }); it('should not reset values if user is resizing', () => { component.hoveredRegion = 1; component.userIsCurrentlyResizing = false; component.xDirection = 1; component.yDirection = 1; component.movedOutOfRegion = false; component.onMouseoutRegion(1); expect(component.hoveredRegion).toBeNull(); expect(component.movedOutOfRegion).toBe(true); // Only the values given below must not change if the user is resizing. expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); }); it('should set start resizing when user clicks mouse down', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.originalImageWidth = 968; component.originalImageHeight = 1707; component.xDirection = 1; component.hoveredRegion = 1; component.userIsCurrentlyResizing = false; component.selectedRegion = null; component.onMousedownRegion(); expect(component.userIsCurrentlyResizing).toBe(true); expect(component.selectedRegion).toBe(1); expect(component.originalRectArea).toEqual({ x: 202.88192749023438, y: 592.8367919921875, width: 441, height: 303 }); }); it('should set start dragging when user clicks mouse down', () => { spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.originalImageWidth = 968; component.originalImageHeight = 1707; component.hoveredRegion = 1; component.userIsCurrentlyDragging = false; component.selectedRegion = null; component.onMousedownRegion(); expect(component.xDirection).toBeUndefined(); expect(component.yDirection).toBeUndefined(); // The above 2 validations make sure that the if statement for // resizing the region doesn't execute. expect(component.userIsCurrentlyDragging).toBe(true); expect(component.selectedRegion).toBe(1); expect(component.originalRectArea).toEqual({ x: 202.88192749023438, y: 592.8367919921875, width: 441, height: 303 }); }); it('should make sure that the user cannot resize or drag the region' + ' while editing the region label', () => { component.userIsCurrentlyDragging = true; component.userIsCurrentlyResizing = true; component.regionLabelEditorMouseUp(); expect(component.userIsCurrentlyDragging).toBe(false); expect(component.userIsCurrentlyResizing).toBe(false); }); it('should reset editor when user clicks \'Clear Image and Regions\'' + ' editor', fakeAsync(() => { spyOn(ngbModal, 'open').and.returnValue(( { result: Promise.resolve('success') }) as NgbModalRef); spyOn(component, 'imageValueChanged'); spyOn(component, 'initializeEditor'); expect(component.value).toEqual({ imagePath: 'img_20210627_214959_mwljsqraka_height_691_width_392.svg', labeledRegions: [ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ] }); component.resetEditor(); tick(); expect(ngbModal.open).toHaveBeenCalledWith( ImageWithRegionsResetConfirmationModalComponent, { backdrop: 'static', keyboard: false }); expect(component.value).toEqual({ imagePath: '', labeledRegions: [] }); expect(component.imageValueChanged).toHaveBeenCalled(); expect(component.initializeEditor).toHaveBeenCalled(); })); it('should reset editor when user clicks \'cancel\'' + ' in the modal', () => { spyOn(ngbModal, 'open').and.returnValue(( { result: Promise.reject('failure') }) as NgbModalRef); spyOn(component, 'imageValueChanged'); spyOn(component, 'initializeEditor'); component.resetEditor(); // Note to developers: // This callback is triggered when the Cancel button is clicked. // No further action is needed. expect(component.imageValueChanged).not.toHaveBeenCalled(); expect(component.initializeEditor).not.toHaveBeenCalled(); }); it('should get schema when function is called', () => { component.SCHEMA = { type: 'custom', obj_type: 'Filepath' }; expect(component.getSchema()).toEqual({ type: 'custom', obj_type: 'Filepath' }); }); it('should track x and y direction changes towards the bottom of the image' + ' while user is moving mouse in the region', () => { component.userIsCurrentlyDragging = false; component.userIsCurrentlyResizing = false; component.hoveredRegion = null; spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.originalImageWidth = 968; component.originalImageHeight = 1707; component.mouseX = 500; component.mouseY = 500; component.resizableBorderWidthPx = 10; component.xDirection = 1; component.yDirection = 1; component.onMouseMoveRegion(0); expect(component.xDirection).toBe(-1); expect(component.yDirection).toBe(-1); }); it('should track x and y direction changes towards the top of the image' + ' while user is moving mouse in the region', () => { component.userIsCurrentlyDragging = false; component.userIsCurrentlyResizing = false; component.hoveredRegion = null; spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.originalImageWidth = 968; component.originalImageHeight = 1707; component.mouseX = 100; component.mouseY = 100; component.resizableBorderWidthPx = 10; component.xDirection = -1; component.yDirection = -1; component.onMouseMoveRegion(0); expect(component.xDirection).toBe(1); expect(component.yDirection).toBe(1); }); it('should track x and y direction changes towards the top of the image' + ' while user is moving mouse in the region', () => { component.userIsCurrentlyDragging = false; component.userIsCurrentlyResizing = false; component.hoveredRegion = null; spyOn(Element.prototype, 'querySelectorAll').and.callFake( jasmine.createSpy('querySelectorAll').and .returnValue([{ getBoundingClientRect: () => { return { bottom: 1468.6285400390625, height: 1297.46533203125, left: 477.1180725097656, right: 1212.8819885253906, top: 171.1632080078125, width: 735.763916015625, x: 477.1180725097656, y: 171.1632080078125 }; } }]) ); component.originalImageWidth = 968; component.originalImageHeight = 1707; component.mouseX = 200; component.mouseY = 200; component.resizableBorderWidthPx = 10; component.xDirection = 1; component.yDirection = 1; component.onMouseMoveRegion(0); expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); }); it('should not track x and y direction changes' + ' while user is dragging the region', () => { component.xDirection = 0; component.yDirection = 0; component.userIsCurrentlyDragging = true; component.onMouseMoveRegion(0); // The values tested below must NOT change when the user is // not resizing or dragging the region. expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); }); it('should not track x and y direction changes' + ' while user is resizing the region', () => { component.xDirection = 0; component.yDirection = 0; component.userIsCurrentlyResizing = true; component.onMouseMoveRegion(0); // The values tested below must NOT change when the user is // not resizing or dragging the region. expect(component.xDirection).toBe(0); expect(component.yDirection).toBe(0); }); it('should delete region when user clicks the trash icon', () => { component.selectedRegion = 1; component.hoveredRegion = 1; expect(component.value.labeledRegions).toEqual([ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ]); component.deleteRegion(1); expect(component.selectedRegion).toBe(null); expect(component.hoveredRegion).toBe(null); expect(component.value.labeledRegions).toEqual([ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } } ]); }); it('should delete region and change hovered and selected region if not null' + ' when user deletes a region', () => { component.selectedRegion = 1; component.hoveredRegion = 1; expect(component.value.labeledRegions).toEqual([ { label: 'Region1', region: { regionType: 'Rectangle', area: [ [ 0.23225103021579202, 0.08157179492961315 ], [ 0.553006091537647, 0.3235816208679242 ] ] } }, { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ]); component.deleteRegion(0); expect(component.selectedRegion).toBe(0); expect(component.hoveredRegion).toBe(0); expect(component.value.labeledRegions).toEqual([ { label: 'Region2', region: { regionType: 'Rectangle', area: [ [ 0.2757432419204503, 0.45691824471291725 ], [ 0.8751202844752727, 0.69045001942409 ] ] } } ]); }); it('should display slanted (225deg) cursor style when user is resizing' + 'ysing the bottom right corner of the region', () => { component.xDirection = 1; component.yDirection = 1; component.xDirectionToggled = true; component.yDirectionToggled = true; expect(component.getCursorStyle()).toBe('se-resize'); }); it('should display slanted (135) cursor style when user is resizing' + 'the region using the top left corner of the region', () => { component.xDirection = -1; component.yDirection = -1; component.xDirectionToggled = true; component.yDirectionToggled = true; expect(component.getCursorStyle()).toBe('nw-resize'); }); it('should display \'pointer\' if user is not resizing but cursor' + ' is over a region', () => { component.hoveredRegion = 0; component.xDirection = 0; component.yDirection = 0; expect(component.getCursorStyle()).toBe('pointer'); }); it('should display \'crosshair\' if user is not resizing and cursor' + ' is not over a region', () => { component.hoveredRegion = null; component.xDirection = 0; component.yDirection = 0; expect(component.getCursorStyle()).toBe('crosshair'); }); it('should display \'s-resize\' cursor style when user is resizing' + 'the region using the bottom side of the region', () => { component.xDirection = 0; component.yDirection = 1; component.xDirectionToggled = false; component.yDirectionToggled = true; expect(component.getCursorStyle()).toBe('s-resize'); }); it('should display \'e-resize\' cursor style when user is resizing' + 'the region using the right side of the region', () => { component.xDirection = 1; component.yDirection = 0; component.xDirectionToggled = true; component.yDirectionToggled = false; expect(component.getCursorStyle()).toBe('e-resize'); }); });
the_stack
import IAccountDataStore from "../../common/IAccountDataStore"; import ILogger from "../../common/ILogger"; import QueueStorageContext from "../context/QueueStorageContext"; import StorageErrorFactory from "../errors/StorageErrorFactory"; import { AccessPolicy } from "../generated/artifacts/models"; import Operation from "../generated/artifacts/operation"; import Context from "../generated/Context"; import IRequest from "../generated/IRequest"; import IQueueMetadataStore from "../persistence/IQueueMetadataStore"; import IAuthenticator from "./IAuthenticator"; import { generateQueueSASSignature, IQueueSASSignatureValues } from "./IQueueSASSignatureValues"; import { OPERATION_QUEUE_SAS_PERMISSIONS } from "./OperationQueueSASPermission"; export default class BlobSASAuthenticator implements IAuthenticator { public constructor( private readonly accountDataStore: IAccountDataStore, private readonly queueMetadataStore: IQueueMetadataStore, private readonly logger: ILogger ) {} public async validate( req: IRequest, context: Context ): Promise<boolean | undefined> { this.logger.info( `QueueSASAuthenticator:validate() Start validation against queue service Shared Access Signature pattern.`, context.contextID ); this.logger.debug( "QueueSASAuthenticator:validate() Getting account properties...", context.contextID ); const queueContext = new QueueStorageContext(context); const account = queueContext.account; if (account === undefined) { throw RangeError( `QueueSASAuthenticator:validate() account is undefined in context.` ); } const queueName = queueContext.queue; if (queueName === undefined) { this.logger.error( `QueueSASAuthenticator:validate() queue name is undefined in context.`, context.contextID ); return undefined; } this.logger.debug( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:validate() Retrieved account name from context: ${account}, queue: ${queueName}`, context.contextID ); // TODO: Make following async const accountProperties = this.accountDataStore.getAccount(account); if (accountProperties === undefined) { throw StorageErrorFactory.getInvalidOperation( context.contextID!, "Invalid storage account." ); } this.logger.debug( "QueueSASAuthenticator:validate() Got account properties successfully.", context.contextID ); // Extract blob service SAS authentication required parameters const signature = this.decodeIfExist(req.getQuery("sig")); this.logger.debug( `QueueSASAuthenticator:validate() Retrieved signature from URL parameter sig: ${signature}`, context.contextID ); if (signature === undefined) { this.logger.debug( `QueueSASAuthenticator:validate() No signature found in request. Skip Queue service SAS validation.`, context.contextID ); return undefined; } const values = this.getQueueSASSignatureValuesFromRequest(req, queueName); if (values === undefined) { this.logger.info( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:validate() Failed to get valid queue service SAS values from request. Skip queue service SAS validation.`, context.contextID ); return undefined; } this.logger.debug( `QueueSASAuthenticator:validate() Successfully got valid queue service SAS values from request. ${JSON.stringify( values )}`, context.contextID ); this.logger.info( `QueueSASAuthenticator:validate() Validate signature based account key1.`, context.contextID ); const [sig1, stringToSign1] = generateQueueSASSignature( values, account, accountProperties.key1 ); this.logger.debug( `QueueSASAuthenticator:validate() String to sign is: ${JSON.stringify( stringToSign1 )}`, context.contextID! ); this.logger.debug( `QueueSASAuthenticator:validate() Calculated signature is: ${sig1}`, context.contextID! ); const sig1Pass = sig1 === signature; this.logger.info( `QueueSASAuthenticator:validate() Signature based on key1 validation ${ sig1Pass ? "passed" : "failed" }.`, context.contextID ); if (!sig1Pass) { if (accountProperties.key2 === undefined) { return false; } this.logger.info( `QueueSASAuthenticator:validate() Account key2 is not empty, validate signature based account key2.`, context.contextID ); const [sig2, stringToSign2] = generateQueueSASSignature( values, account, accountProperties.key2 ); this.logger.debug( `QueueSASAuthenticator:validate() String to sign is: ${JSON.stringify( stringToSign2 )}`, context.contextID! ); this.logger.debug( `QueueSASAuthenticator:validate() Calculated signature is: ${sig2}`, context.contextID! ); const sig2Pass = sig2 !== signature; this.logger.info( `QueueSASAuthenticator:validate() Signature based on key2 validation ${ sig2Pass ? "passed" : "failed" }.`, context.contextID ); if (!sig2Pass) { this.logger.info( `QueueSASAuthenticator:validate() Validate signature based account key1 and key2 failed.`, context.contextID ); return false; } } // When signature validation passes, we enforce queue service SAS validation // Any validation errors will stop this request immediately // TODO: Validate permissions from ACL identifier by extract permissions, start time and expiry time from ACL // TODO: Set ACL without given start time. if (values.identifier !== undefined) { const accessPolicy: | AccessPolicy | undefined = await this.getQueueAccessPolicyByIdentifier( account, queueName, values.identifier ); if (accessPolicy === undefined) { this.logger.warn( `QueueSASAuthenticator:validate() Cannot get access policy defined for queue ${queueName} with id ${ values.identifier }.`, context.contextID ); throw StorageErrorFactory.getAuthorizationFailure(context.contextID!); } // As Azure Storage, SAS with indentifier should not contains any overlap values. if ( values.startTime !== undefined || values.expiryTime !== undefined || values.permissions !== undefined ) { throw StorageErrorFactory.getAuthorizationFailure(context.contextID!); } values.startTime = accessPolicy.start; values.expiryTime = accessPolicy.expiry; values.permissions = accessPolicy.permission; } this.logger.info( `QueueSASAuthenticator:validate() Validate start and expiry time.`, context.contextID ); if (!this.validateTime(values.expiryTime, values.startTime)) { this.logger.info( `QueueSASAuthenticator:validate() Validate start and expiry failed.`, context.contextID ); throw StorageErrorFactory.getAuthorizationFailure(context.contextID!); } this.logger.info( `QueueSASAuthenticator:validate() Validate IP range.`, context.contextID ); if (!this.validateIPRange()) { this.logger.info( `QueueSASAuthenticator:validate() Validate IP range failed.`, context.contextID ); throw StorageErrorFactory.getAuthorizationSourceIPMismatch( context.contextID! ); } this.logger.info( `QueueSASAuthenticator:validate() Validate request protocol.`, context.contextID ); if (!this.validateProtocol(values.protocol, req.getProtocol())) { this.logger.info( `QueueSASAuthenticator:validate() Validate protocol failed.`, context.contextID ); throw StorageErrorFactory.getAuthorizationProtocolMismatch( context.contextID! ); } const operation = context.operation; if (operation === undefined) { throw new Error( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:validate() Operation shouldn't be undefined. Please make sure DispatchMiddleware is hooked before authentication related middleware.` ); } const queueSASPermission = OPERATION_QUEUE_SAS_PERMISSIONS.get(operation); this.logger.debug( `QueueSASAuthenticator:validate() Got permission requirements for operation ${ Operation[operation] } - ${JSON.stringify(queueSASPermission)}`, context.contextID ); if (queueSASPermission === undefined) { throw new Error( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:validate() OPERATION_QUEUE_SAS_PERMISSIONS doesn't have configuration for operation ${ Operation[operation] }'s queue service SAS permission.` ); } if (!queueSASPermission.validatePermissions(values.permissions!)) { throw StorageErrorFactory.getAuthorizationPermissionMismatch( context.contextID! ); } return true; } private getQueueSASSignatureValuesFromRequest( req: IRequest, queueName: string ): IQueueSASSignatureValues | undefined { const version = this.decodeIfExist(req.getQuery("sv")); const protocol = this.decodeIfExist(req.getQuery("spr")); const startTime = this.decodeIfExist(req.getQuery("st")); const expiryTime = this.decodeIfExist(req.getQuery("se")); const permissions = this.decodeIfExist(req.getQuery("sp")); const ipRange = this.decodeIfExist(req.getQuery("sip")); const identifier = this.decodeIfExist(req.getQuery("si")); if (!identifier && (!permissions || !expiryTime)) { this.logger.warn( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:generateQueueSASSignature(): Must provide 'permissions' and 'expiryTime' for Queue SAS generation when 'identifier' is not provided.` ); return undefined; } if (version === undefined) { this.logger.warn( // tslint:disable-next-line:max-line-length `QueueSASAuthenticator:generateQueueSASSignature(): Must provide 'version'.` ); return undefined; } const queueSASValues: IQueueSASSignatureValues = { version, protocol, startTime, expiryTime, permissions, ipRange, identifier, queueName }; return queueSASValues; } private validateTime(expiry?: Date | string, start?: Date | string): boolean { // The same as Azure storage, each part is required. if (expiry === undefined || start === undefined) { return false; } const now = new Date(); if (expiry !== undefined) { const expiryTime = new Date(expiry); if (now > expiryTime) { return false; } } if (start !== undefined) { const startTime = new Date(start); if (now < startTime) { return false; } } return true; } private validateIPRange(): boolean { // TODO: Emulator doesn't validate IP Address return true; } private validateProtocol( sasProtocol: string = "https,http", requestProtocol: string ): boolean { if (sasProtocol.includes(",")) { return true; } else { return sasProtocol.toLowerCase() === requestProtocol; } } private decodeIfExist(value?: string): string | undefined { return value === undefined ? value : decodeURIComponent(value); } private async getQueueAccessPolicyByIdentifier( account: string, queue: string, id: string ): Promise<AccessPolicy | undefined> { try { const queueModel = await this.queueMetadataStore.getQueue(account, queue); if (queueModel === undefined) { return undefined; } if (queueModel.queueAcl === undefined) { return undefined; } for (const acl of queueModel.queueAcl) { if (acl.id === id) { return acl.accessPolicy; } } return undefined; } catch (err) { return undefined; } } }
the_stack
import { Database } from '../../src/database' import { expect } from 'chai' import * as support from '../support' interface Record { key: string index: number } /** Gives a empty database context */ async function use(func: (database: Database) => Promise<void>): Promise<void> { const dbname = support.uuid() const database = new Database(dbname) await func(database) await database.dispose() await Database.drop(dbname) } /** Gives a database context with 1024 populated records */ async function useWithRecords(func: (database: Database) => Promise<void>): Promise<void> { const dbname = support.uuid() const database = new Database(dbname) for (const index of support.range(1024)) { const key = support.uuid() database.insert('records', { key, index }) } await database.commit() await func(database) await database.dispose() await Database.drop(dbname) } describe('Database', () => { // #region nonexistent store mutations it('should count on nonexistent store.', async () => { await use(async database => { const store = support.uuid() const result = await database.count(store) expect(result).to.be.eq(0) }) }) it('should get on nonexistent store.', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() const result = await database.get(store, key) expect(result).to.be.undefined }) }) it('should query on nonexistent store.', async () => { await use(async database => { const store = support.uuid() const result = await database.query(store).toArray() expect(result).to.have.lengthOf(0) }) }) it('should insert on nonexistent store.', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() database.insert(store, { key }) await database.commit() }) }) it(`should test true for 'exists'`, async () => { await use(async database => { const store = support.uuid() const key = support.uuid() const result0 = await database.exists(store, key) database.insert(store, { key }) await database.commit() const result1 = await database.exists(store, key) database.delete(store, { key }) await database.commit() const result2 = await database.exists(store, key) expect(result0).to.be.false expect(result1).to.be.true expect(result2).to.be.false }) }) // #region top level database interactions it('should get name', async () => { await use(async database => { const result = await database.name() expect(result).to.not.be.undefined }) }) it('should get version', async () => { await use(async database => { const result = await database.version() expect(result).to.not.be.undefined }) }) it('should insert and get', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() database.insert(store, { key }) await database.commit() const record = await database.get(store, key) expect(record).to.not.be.undefined }) }) it('should insert and update', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() const value = support.uuid() database.insert(store, { key }) await database.commit() await database.update(store, { key, value }) await database.commit() const record = (await database.get(store, key)) as any expect(record.value).to.eq(value) }) }) it('should insert and delete', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() database.insert(store, { key }) await database.commit() const record0 = await database.get(store, key) expect(record0).to.not.be.undefined await database.delete(store, { key }) await database.commit() const record1 = await database.get(store, key) expect(record1).to.be.undefined }) }) it('should insert and delete with string key', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() database.insert(store, { key }) await database.commit() const record0 = await database.get(store, key) expect(record0).to.not.be.undefined await database.delete(store, key) await database.commit() const record1 = await database.get(store, key) expect(record1).to.be.undefined }) }) it('should insert 256 records in single store and count', async () => { await use(async database => { const count = 32 const store = support.uuid() const keys = support.range(count).map(n => support.uuid()) for (const key of keys) { database.insert(store, { key }) } await database.commit() const result = await database.count(store) expect(result).to.be.eq(count) }) }) it('should insert 8 stores with 1 record and count stores', async () => { await use(async database => { const count = 8 const stores = support.range(count).map(n => support.uuid()) const key = support.uuid() for (const store of stores) { database.insert(store, { key }) } await database.commit() const result = await database.stores() expect(result).to.have.lengthOf(count) }) }) it('should insert and drop store', async () => { await use(async database => { const store = support.uuid() const key = support.uuid() database.insert(store, { key }) await database.commit() const result0 = await database.get(store, key) expect(result0).to.not.be.undefined await database.drop(store) const result1 = await database.get(store, key) expect(result1).to.be.undefined }) }) // #region query it(`should run query with 'toArray'`, async () => { await useWithRecords(async database => { const result = await database.query<Record>('records').toArray() expect(result).to.have.lengthOf(1024) }) }) it(`should run query with 'aggregate'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => 1) .aggregate((acc, c) => acc + c, 0) expect(result).to.be.eq(1024) }) }) it(`should run query with 'all' > true`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .all(n => n.index >= 0 && n.index < 1024) expect(result).to.be.eq(true) }) }) it(`should run query with 'all' > false`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .all(n => n.index > 0 && n.index < 1024) expect(result).to.be.eq(false) }) }) it(`should run query with 'average'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => 1) .average(n => n) expect(result).to.be.eq(1) }) }) it(`should run query with 'any' > true`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .any(n => n.index > 0) expect(result).to.be.eq(true) }) }) it(`should run query with 'any' > false`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .any(n => n.index < 0) expect(result).to.be.eq(false) }) }) it(`should run query with 'concat'`, async () => { await useWithRecords(async database => { const query0 = await database .query<Record>('records') .select(n => n.index) const query1 = await database .query<Record>('records') .select(n => n.index + 1024) const query2 = query0.concat(query1).orderBy(n => n) const array = await query2.toArray() for (let i = 0; i < 2048; i++) { expect(array[i]).to.eq(i) } }) }) it(`should run query with 'count'`, async () => { await useWithRecords(async database => { const result = await database.query<Record>('records').count() expect(result).to.be.eq(1024) }) }) it(`should run query with 'distinct'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => n.index % 4) .distinct(n => n) .toArray() expect(result).to.have.lengthOf(4) }) }) it(`should run query with 'elementAt'`, async () => { await useWithRecords(async database => { const result0 = await database .query<Record>('records') .orderBy(n => n.index) .elementAt(0) const result1 = await database .query<Record>('records') .orderBy(n => n.index) .elementAt(128) const result2 = await database .query<Record>('records') .orderBy(n => n.index) .elementAt(256) const result3 = await database .query<Record>('records') .orderBy(n => n.index) .elementAt(512) const result4 = await database .query<Record>('records') .orderBy(n => n.index) .elementAt(1025) expect(result0!.index).to.be.eq(0) expect(result1!.index).to.be.eq(128) expect(result2!.index).to.be.eq(256) expect(result3!.index).to.be.eq(512) expect(result4).to.be.undefined }) }) it(`should run query with 'first'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderBy(n => n.index) .first() expect(result!.index).to.be.eq(0) }) }) it(`should run query with 'last'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderByDescending(n => n.index) .last() expect(result!.index).to.be.eq(0) }) }) it(`should run query with 'orderBy'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderBy(n => n.index) .first() expect(result!.index).to.be.eq(0) }) }) it(`should run query with 'orderByDescending'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderByDescending(n => n.index) .first() expect(result!.index).to.be.eq(1023) }) }) it(`should run query with 'reverse'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderByDescending(n => n.index) .reverse() .first() expect(result!.index).to.be.eq(0) }) }) it(`should run query with 'select'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => n.index) .toArray() expect(result).to.have.lengthOf(1024) }) }) it(`should run query with 'selectMany'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => [n.index, 1]) .selectMany(n => n) .toArray() expect(result).to.have.lengthOf(2048) }) }) it(`should run query with 'skip'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderBy(n => n.index) .skip(512) .toArray() expect(result).to.have.lengthOf(512) expect(result[0].index).to.be.eq(512) }) }) it(`should run query with 'sum'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .select(n => 1) .sum(n => n) expect(result).to.be.eq(1024) }) }) it(`should run query with 'take'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderBy(n => n.index) .take(512) .toArray() expect(result).to.have.lengthOf(512) expect(result[0].index).to.be.eq(0) expect(result[511].index).to.be.eq(511) }) }) it(`should run query with 'where'`, async () => { await useWithRecords(async database => { const result = await database .query<Record>('records') .orderBy(n => n.index) .where(n => n.index < 512) .toArray() expect(result).to.have.lengthOf(512) expect(result[0].index).to.be.eq(0) expect(result[511].index).to.be.eq(511) }) }) // #region enumeration it(`should enumerate records with 'asyncIterator'`, async () => { await useWithRecords(async database => { const query = await database.query<Record>('records') let count = 0 for await (const record of query) { expect(record).to.not.be.undefined count++ } expect(count).to.eq(1024) }) }) // #region drop database it(`should 'drop' database and re-open and test empty`, async () => { const name = support.uuid() const key = support.uuid() const store = support.uuid() const db0 = new Database(name) db0.insert(store, { key }) await db0.commit() const result0 = await db0.get(store, key) expect(result0).to.not.be.undefined await db0.dispose() await Database.drop(name) const db1 = new Database(name) const result1 = await db1.get(store, key) expect(result1).to.be.undefined }) })
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/meshApplicationMappers"; import * as Parameters from "../models/parameters"; import { ServiceFabricClientContext } from "../serviceFabricClientContext"; /** Class representing a MeshApplication. */ export class MeshApplication { private readonly client: ServiceFabricClientContext; /** * Create a MeshApplication. * @param {ServiceFabricClientContext} client Reference to the service client. */ constructor(client: ServiceFabricClientContext) { this.client = client; } /** * Creates a Application resource with the specified name, description and properties. If * Application resource with the same name exists, then it is updated with the specified * description and properties. * @summary Creates or updates a Application resource. * @param applicationResourceName The identity of the application. * @param applicationResourceDescription Description for creating a Application resource. * @param [options] The optional parameters * @returns Promise<Models.MeshApplicationCreateOrUpdateResponse> */ createOrUpdate(applicationResourceName: string, applicationResourceDescription: Models.ApplicationResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.MeshApplicationCreateOrUpdateResponse>; /** * @param applicationResourceName The identity of the application. * @param applicationResourceDescription Description for creating a Application resource. * @param callback The callback */ createOrUpdate(applicationResourceName: string, applicationResourceDescription: Models.ApplicationResourceDescription, callback: msRest.ServiceCallback<Models.ApplicationResourceDescription>): void; /** * @param applicationResourceName The identity of the application. * @param applicationResourceDescription Description for creating a Application resource. * @param options The optional parameters * @param callback The callback */ createOrUpdate(applicationResourceName: string, applicationResourceDescription: Models.ApplicationResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationResourceDescription>): void; createOrUpdate(applicationResourceName: string, applicationResourceDescription: Models.ApplicationResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationResourceDescription>, callback?: msRest.ServiceCallback<Models.ApplicationResourceDescription>): Promise<Models.MeshApplicationCreateOrUpdateResponse> { return this.client.sendOperationRequest( { applicationResourceName, applicationResourceDescription, options }, createOrUpdateOperationSpec, callback) as Promise<Models.MeshApplicationCreateOrUpdateResponse>; } /** * Gets the information about the Application resource with the given name. The information include * the description and other properties of the Application. * @summary Gets the Application resource with the given name. * @param applicationResourceName The identity of the application. * @param [options] The optional parameters * @returns Promise<Models.MeshApplicationGetResponse> */ get(applicationResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.MeshApplicationGetResponse>; /** * @param applicationResourceName The identity of the application. * @param callback The callback */ get(applicationResourceName: string, callback: msRest.ServiceCallback<Models.ApplicationResourceDescription>): void; /** * @param applicationResourceName The identity of the application. * @param options The optional parameters * @param callback The callback */ get(applicationResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationResourceDescription>): void; get(applicationResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationResourceDescription>, callback?: msRest.ServiceCallback<Models.ApplicationResourceDescription>): Promise<Models.MeshApplicationGetResponse> { return this.client.sendOperationRequest( { applicationResourceName, options }, getOperationSpec, callback) as Promise<Models.MeshApplicationGetResponse>; } /** * Deletes the Application resource identified by the name. * @summary Deletes the Application resource. * @param applicationResourceName The identity of the application. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(applicationResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param applicationResourceName The identity of the application. * @param callback The callback */ deleteMethod(applicationResourceName: string, callback: msRest.ServiceCallback<void>): void; /** * @param applicationResourceName The identity of the application. * @param options The optional parameters * @param callback The callback */ deleteMethod(applicationResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(applicationResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { applicationResourceName, options }, deleteMethodOperationSpec, callback); } /** * Gets the information about all application resources in a given resource group. The information * include the description and other properties of the Application. * @summary Lists all the application resources. * @param [options] The optional parameters * @returns Promise<Models.MeshApplicationListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.MeshApplicationListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.PagedApplicationResourceDescriptionList>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PagedApplicationResourceDescriptionList>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PagedApplicationResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.PagedApplicationResourceDescriptionList>): Promise<Models.MeshApplicationListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.MeshApplicationListResponse>; } /** * Gets the upgrade progress information about the Application resource with the given name. The * information include percentage of completion and other upgrade state information of the * Application resource. * @summary Gets the progress of the latest upgrade performed on this application resource. * @param applicationResourceName The identity of the application. * @param [options] The optional parameters * @returns Promise<Models.MeshApplicationGetUpgradeProgressResponse> */ getUpgradeProgress(applicationResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.MeshApplicationGetUpgradeProgressResponse>; /** * @param applicationResourceName The identity of the application. * @param callback The callback */ getUpgradeProgress(applicationResourceName: string, callback: msRest.ServiceCallback<Models.ApplicationResourceUpgradeProgressInfo>): void; /** * @param applicationResourceName The identity of the application. * @param options The optional parameters * @param callback The callback */ getUpgradeProgress(applicationResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApplicationResourceUpgradeProgressInfo>): void; getUpgradeProgress(applicationResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApplicationResourceUpgradeProgressInfo>, callback?: msRest.ServiceCallback<Models.ApplicationResourceUpgradeProgressInfo>): Promise<Models.MeshApplicationGetUpgradeProgressResponse> { return this.client.sendOperationRequest( { applicationResourceName, options }, getUpgradeProgressOperationSpec, callback) as Promise<Models.MeshApplicationGetUpgradeProgressResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "Resources/Applications/{applicationResourceName}", urlParameters: [ Parameters.applicationResourceName ], queryParameters: [ Parameters.apiVersion8 ], requestBody: { parameterPath: "applicationResourceDescription", mapper: { ...Mappers.ApplicationResourceDescription, required: true } }, responses: { 200: { bodyMapper: Mappers.ApplicationResourceDescription }, 201: { bodyMapper: Mappers.ApplicationResourceDescription }, 202: {}, default: { bodyMapper: Mappers.FabricError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "Resources/Applications/{applicationResourceName}", urlParameters: [ Parameters.applicationResourceName ], queryParameters: [ Parameters.apiVersion8 ], responses: { 200: { bodyMapper: Mappers.ApplicationResourceDescription }, default: { bodyMapper: Mappers.FabricError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "Resources/Applications/{applicationResourceName}", urlParameters: [ Parameters.applicationResourceName ], queryParameters: [ Parameters.apiVersion8 ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.FabricError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "Resources/Applications", queryParameters: [ Parameters.apiVersion8 ], responses: { 200: { bodyMapper: Mappers.PagedApplicationResourceDescriptionList }, default: { bodyMapper: Mappers.FabricError } }, serializer }; const getUpgradeProgressOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "Resources/Applications/{applicationResourceName}/$/GetUpgradeProgress", urlParameters: [ Parameters.applicationResourceName ], queryParameters: [ Parameters.apiVersion3 ], responses: { 200: { bodyMapper: Mappers.ApplicationResourceUpgradeProgressInfo }, default: { bodyMapper: Mappers.FabricError } }, serializer };
the_stack
import { Component } from '../component'; import { DOMUtils } from '../../services'; import { Events, Roles, ColorClassNameTypes, RenderTypes, Alignments, } from '../../interfaces'; import { Tools } from '../../tools'; import { Point, Angle, radialLabelPlacement, radToDeg, polarToCartesianCoords, distanceBetweenPointOnCircAndVerticalDiameter, } from '../../services/angle-utils'; import * as Configuration from '../../configuration'; // D3 Imports import { select } from 'd3-selection'; import { scaleBand, scaleLinear } from 'd3-scale'; import { max, min, extent } from 'd3-array'; import { lineRadial, curveLinearClosed } from 'd3-shape'; export class Radar extends Component { type = 'radar'; renderType = RenderTypes.SVG; svg: SVGElement; groupMapsTo: string; uniqueKeys: string[]; uniqueGroups: string[]; fullDataNormalized: any; groupedDataNormalized: any; init() { const { events } = this.services; // Highlight correct line legend item hovers events.addEventListener( Events.Legend.ITEM_HOVER, this.handleLegendOnHover ); // Un-highlight lines on legend item mouseouts events.addEventListener( Events.Legend.ITEM_MOUSEOUT, this.handleLegendMouseOut ); } render(animate = true) { const svg = this.getComponentContainer(); const { width, height } = DOMUtils.getSVGElementSize(svg, { useAttrs: true, }); const data = this.model.getData(); const groupedData = this.model.getGroupedData(); const options = this.getOptions(); const groupMapsTo = Tools.getProperty(options, 'data', 'groupMapsTo'); const valueMapsTo = Tools.getProperty( options, 'radar', 'axes', 'value' ); const { angle, value } = Tools.getProperty(options, 'radar', 'axes'); const { xLabelPadding, yLabelPadding, yTicksNumber, minRange, xAxisRectHeight, } = Configuration.radar; this.uniqueKeys = Array.from(new Set(data.map((d) => d[angle]))); this.uniqueGroups = Array.from( new Set(data.map((d) => d[groupMapsTo])) ); this.fullDataNormalized = this.normalizeFlatData(data); this.groupedDataNormalized = this.normalizeGroupedData(groupedData); const labelHeight = this.getLabelDimensions(this.uniqueKeys[0]).height; const margin = 2 * (labelHeight + yLabelPadding); const size = Math.min(width, height); const diameter = size - margin; const radius = diameter / 2; if (radius <= 0) { return; } // given a key, return the corresponding angle in radiants // rotated by -PI/2 because we want angle 0° at -y (12 o’clock) const xScale = scaleBand<string>() .domain(this.fullDataNormalized.map((d) => d[angle])) .range( [0, 2 * Math.PI].map((a) => a - Math.PI / 2) as [Angle, Angle] ); const centerPointMinValue = min( this.fullDataNormalized.map((d) => d[value]) as number[] ); const yScale = scaleLinear() .domain([ centerPointMinValue >= 0 ? 0 : centerPointMinValue, max(this.fullDataNormalized.map((d) => d[value]) as number[]), ]) .range([minRange, radius]) .nice(yTicksNumber); const yTicks = yScale.ticks(yTicksNumber); const colorScale = (group: string): string => this.model.getFillColor(group); // constructs a new radial line generator // the angle accessor returns the angle in radians with 0° at -y (12 o’clock) // so map back the angle const radialLineGenerator = lineRadial<any>() .angle((d) => xScale(d[angle]) + Math.PI / 2) .radius((d) => yScale(d[value])) .curve(curveLinearClosed); // compute the space that each x label needs const horizSpaceNeededByEachXLabel = this.uniqueKeys.map((key) => { const tickWidth = this.getLabelDimensions(key).width; // compute the distance between the point that the label rapresents and the vertical diameter const distanceFromDiameter = distanceBetweenPointOnCircAndVerticalDiameter( xScale(key), radius ); // the space each label occupies is the sum of these two values return tickWidth + distanceFromDiameter; }); const leftPadding = max(horizSpaceNeededByEachXLabel); // center coordinates const c: Point = { x: leftPadding + xLabelPadding, y: height / 2, }; ///////////////////////////// // Drawing the radar ///////////////////////////// // y axes const yAxes = DOMUtils.appendOrSelect(svg, 'g.y-axes').attr( 'role', Roles.GROUP ); const yAxisUpdate = yAxes .selectAll('path') .data(yTicks, (tick) => tick); // for each tick, create array of data corresponding to the points composing the shape const shapeData = (tick: number) => this.uniqueKeys.map((key) => ({ [angle]: key, [value]: tick })); yAxisUpdate.join( (enter) => enter .append('path') .attr('opacity', 0) .attr('transform', `translate(${c.x}, ${c.y})`) .attr('fill', 'none') .call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_axes_enter', animate, }) ) .attr('opacity', 1) .attr('d', (tick) => radialLineGenerator(shapeData(tick)) ) ), (update) => update.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_axes_update', animate, }) ) .attr('opacity', 1) .attr('transform', `translate(${c.x}, ${c.y})`) .attr('d', (tick) => radialLineGenerator(shapeData(tick)) ) ), (exit) => exit.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_axes_exit', animate, }) ) .attr('d', (tick) => radialLineGenerator(shapeData(tick)) ) .attr('opacity', 0) .remove() ) ); // x axes const xAxes = DOMUtils.appendOrSelect(svg, 'g.x-axes').attr( 'role', Roles.GROUP ); const xAxisUpdate = xAxes .selectAll('line') .data(this.uniqueKeys, (key) => key); xAxisUpdate.join( (enter) => enter .append('line') .attr('opacity', 0) .attr('class', (key) => `x-axis-${Tools.kebabCase(key)}`) // replace spaces with - .attr('stroke-dasharray', '0') .attr( 'x1', (key) => polarToCartesianCoords(xScale(key), 0, c).x ) .attr( 'y1', (key) => polarToCartesianCoords(xScale(key), 0, c).y ) .attr( 'x2', (key) => polarToCartesianCoords(xScale(key), 0, c).x ) .attr( 'y2', (key) => polarToCartesianCoords(xScale(key), 0, c).y ) .call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_axes_enter', animate, }) ) .attr('opacity', 1) .attr( 'x1', (key) => polarToCartesianCoords( xScale(key), yScale.range()[0], c ).x ) .attr( 'y1', (key) => polarToCartesianCoords( xScale(key), yScale.range()[0], c ).y ) .attr( 'x2', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1], c ).x ) .attr( 'y2', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1], c ).y ) ), (update) => update.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_axes_update', animate, }) ) .attr('opacity', 1) .attr( 'x1', (key) => polarToCartesianCoords( xScale(key), yScale.range()[0], c ).x ) .attr( 'y1', (key) => polarToCartesianCoords( xScale(key), yScale.range()[0], c ).y ) .attr( 'x2', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1], c ).x ) .attr( 'y2', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1], c ).y ) ), (exit) => exit.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_axes_exit', animate, }) ) .attr('opacity', 0) .remove() ) ); // x labels const xLabels = DOMUtils.appendOrSelect(svg, 'g.x-labels').attr( 'role', Roles.GROUP ); const xLabelUpdate = xLabels.selectAll('text').data(this.uniqueKeys); xLabelUpdate.join( (enter) => enter .append('text') .text((key) => key) .attr('opacity', 0) .attr( 'x', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1] + xLabelPadding, c ).x ) .attr( 'y', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1] + xLabelPadding, c ).y ) .style( 'text-anchor', (key) => radialLabelPlacement(xScale(key)).textAnchor ) .style( 'dominant-baseline', (key) => radialLabelPlacement(xScale(key)).dominantBaseline ) .call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_labels_enter', animate, }) ) .attr('opacity', 1) ), (update) => update.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_labels_update', animate, }) ) .attr('opacity', 1) .attr( 'x', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1] + xLabelPadding, c ).x ) .attr( 'y', (key) => polarToCartesianCoords( xScale(key), yScale.range()[1] + xLabelPadding, c ).y ) ), (exit) => exit.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_x_labels_exit', animate, }) ) .attr('opacity', 0) .remove() ) ); // blobs const blobs = DOMUtils.appendOrSelect(svg, 'g.blobs').attr( 'role', Roles.GROUP ); const blobUpdate = blobs .selectAll('path') .data(this.groupedDataNormalized, (group) => group.name); blobUpdate.join( (enter) => enter .append('path') .attr('class', (group) => this.model.getColorClassName({ classNameTypes: [ ColorClassNameTypes.FILL, ColorClassNameTypes.STROKE, ], dataGroupName: group.name, originalClassName: 'blob', }) ) .attr('role', Roles.GRAPHICS_SYMBOL) .attr('aria-label', (d) => d['name']) .attr('opacity', 0) .attr( 'transform', animate ? () => `translate(${c.x}, ${c.y}) scale(${ 1 + Math.random() * 0.35 })` : `translate(${c.x}, ${c.y})` ) .style('fill', (group) => colorScale(group.name)) .style('fill-opacity', Configuration.radar.opacity.selected) .style('stroke', (group) => colorScale(group.name)) .call((selection) => { const selectionUpdate = selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_blobs_enter', animate, }) ); if (animate) { selectionUpdate .delay(() => Math.random() * 30) .attr('transform', `translate(${c.x}, ${c.y})`); } selectionUpdate .attr('opacity', 1) .attr('d', (group) => radialLineGenerator(group.data) ); }), (update) => { update .attr('class', (group) => this.model.getColorClassName({ classNameTypes: [ ColorClassNameTypes.FILL, ColorClassNameTypes.STROKE, ], dataGroupName: group.name, originalClassName: 'blob', }) ) .style('fill', (group) => colorScale(group.name)) .style('stroke', (group) => colorScale(group.name)); update.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_blobs_update', animate, }) ) .attr('opacity', 1) .attr('transform', `translate(${c.x}, ${c.y})`) .attr('d', (group) => radialLineGenerator(group.data)) ); }, (exit) => exit.call((selection) => { const selectionUpdate = selection.transition().call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_blobs_exit', animate, }) ); if (animate) { selectionUpdate .delay(() => Math.random() * 30) .attr( 'transform', () => `translate(${c.x}, ${c.y}) scale(${ 1 + Math.random() * 0.35 })` ); } selectionUpdate.attr('opacity', 0).remove(); }) ); // data dots const dots = DOMUtils.appendOrSelect(svg, 'g.dots').attr( 'role', Roles.GROUP ); const dotsUpdate = dots .selectAll('circle') // Filter out dots with no value so they are not rendered .data( this.fullDataNormalized.filter( (d) => Tools.getProperty(d, value) !== null ) ); dotsUpdate .join( (enter) => enter .append('circle') .attr('role', Roles.GRAPHICS_SYMBOL) .attr('aria-label', (d) => d[valueMapsTo]), (update) => update, (exit) => exit.remove() ) .attr('class', (d) => this.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.FILL], dataGroupName: d[groupMapsTo], originalClassName: Tools.kebabCase(d[angle]), }) ) .attr( 'cx', (d) => polarToCartesianCoords( xScale(d[angle]), yScale(d[value]), c ).x ) .attr( 'cy', (d) => polarToCartesianCoords( xScale(d[angle]), yScale(d[value]), c ).y ) .attr('r', 0) .attr('opacity', 0) .style('fill', (d) => colorScale(d[groupMapsTo])); // rectangles const xAxesRect = DOMUtils.appendOrSelect(svg, 'g.x-axes-rect').attr( 'role', Roles.GROUP ); const xAxisRectUpdate = xAxesRect .selectAll('rect') .data(this.uniqueKeys); xAxisRectUpdate .join( (enter) => enter.append('rect'), (update) => update, (exit) => exit.remove() ) .attr('x', c.x) .attr('y', c.y - xAxisRectHeight / 2) .attr('width', yScale.range()[1]) .attr('height', xAxisRectHeight) .style('fill', 'red') .style('fill-opacity', 0) .attr( 'transform', (key) => `rotate(${radToDeg(xScale(key))}, ${c.x}, ${c.y})` ); // y labels (show only the min and the max labels) const yLabels = DOMUtils.appendOrSelect(svg, 'g.y-labels').attr( 'role', Roles.GROUP ); const yLabelUpdate = yLabels.selectAll('text').data(extent(yTicks)); yLabelUpdate.join( (enter) => enter .append('text') .attr('opacity', 0) .text((tick) => tick) .attr( 'x', (tick) => polarToCartesianCoords( -Math.PI / 2, yScale(tick), c ).x + yLabelPadding ) .attr( 'y', (tick) => polarToCartesianCoords( -Math.PI / 2, yScale(tick), c ).y ) .style('text-anchor', 'start') .style('dominant-baseline', 'middle') .call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_labels_enter', animate, }) ) .attr('opacity', 1) ), (update) => update.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_labels_update', animate, }) ) .text((tick) => tick) .attr('opacity', 1) .attr( 'x', (tick) => polarToCartesianCoords( -Math.PI / 2, yScale(tick), c ).x + yLabelPadding ) .attr( 'y', (tick) => polarToCartesianCoords( -Math.PI / 2, yScale(tick), c ).y ) ), (exit) => exit.call((selection) => selection .transition() .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'radar_y_labels_exit', animate, }) ) .attr('opacity', 0) .remove() ) ); const alignment = Tools.getProperty(options, 'radar', 'alignment'); const alignmentXOffset = this.getAlignmentXOffset( alignment, svg, this.getParent() ); svg.attr('x', alignmentXOffset); // Add event listeners this.addEventListeners(); } getAlignmentXOffset(alignment, svg, parent) { const svgDimensions = DOMUtils.getSVGElementSize(svg, { useBBox: true, }); const { width } = DOMUtils.getSVGElementSize(parent, { useAttrs: true, }); let alignmentOffset = 0; if (alignment === Alignments.CENTER) { alignmentOffset = Math.floor((width - svgDimensions.width) / 2); } else if (alignment === Alignments.RIGHT) { alignmentOffset = width - svgDimensions.width; } return alignmentOffset; } // append temporarily the label to get the exact space that it occupies getLabelDimensions = (label: string) => { const tmpTick = DOMUtils.appendOrSelect( this.getComponentContainer(), `g.tmp-tick` ); const tmpTickText = DOMUtils.appendOrSelect(tmpTick, `text`).text( label ); const { width, height } = DOMUtils.getSVGElementSize( tmpTickText.node(), { useBBox: true } ); tmpTick.remove(); return { width, height }; }; // Given a flat array of objects, if there are missing data on key, // creates corresponding data with value = null normalizeFlatData = (dataset: any) => { const options = this.getOptions(); const { angle, value } = Tools.getProperty(options, 'radar', 'axes'); const groupMapsTo = Tools.getProperty(options, 'data', 'groupMapsTo'); const completeBlankData = Tools.flatMapDeep( this.uniqueKeys.map((key) => { return this.uniqueGroups.map((group) => ({ [angle]: key, [groupMapsTo]: group, [value]: null, })); }) ); return Tools.merge(completeBlankData, dataset); }; // Given a a grouped array of objects, if there are missing data on key, // creates corresponding data with value = null normalizeGroupedData = (dataset: any) => { const options = this.getOptions(); const { angle, value } = Tools.getProperty(options, 'radar', 'axes'); const groupMapsTo = Tools.getProperty(options, 'data', 'groupMapsTo'); return dataset.map(({ name, data }) => { const completeBlankData = this.uniqueKeys.map((k) => ({ [groupMapsTo]: name, [angle]: k, [value]: null, })); return { name, data: Tools.merge(completeBlankData, data) }; }); }; handleLegendOnHover = (event: CustomEvent) => { const { hoveredElement } = event.detail; this.parent .selectAll('g.blobs path') .transition('legend-hover-blob') .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'legend-hover-blob', }) ) .style('fill-opacity', (group) => { if (group.name !== hoveredElement.datum().name) { return Configuration.radar.opacity.unselected; } return Configuration.radar.opacity.selected; }) .style('stroke-opacity', (group) => { if (group.name !== hoveredElement.datum().name) { return Configuration.radar.opacity.unselected; } return 1; }); }; handleLegendMouseOut = (event: CustomEvent) => { this.parent .selectAll('g.blobs path') .transition('legend-mouseout-blob') .call((t) => this.services.transitions.setupTransition({ transition: t, name: 'legend-mouseout-blob', }) ) .style('fill-opacity', Configuration.radar.opacity.selected) .style('stroke-opacity', 1); }; destroy() { // Remove event listeners this.parent .selectAll('.x-axes-rect > rect') .on('mouseover', null) .on('mousemove', null) .on('mouseout', null); // Remove legend listeners const eventsFragment = this.services.events; eventsFragment.removeEventListener( Events.Legend.ITEM_HOVER, this.handleLegendOnHover ); eventsFragment.removeEventListener( Events.Legend.ITEM_MOUSEOUT, this.handleLegendMouseOut ); } addEventListeners() { const self = this; const { axes: { angle }, } = Tools.getProperty(this.getOptions(), 'radar'); // events on x axes rects this.parent .selectAll('.x-axes-rect > rect') .on('mouseover', function (event, datum) { const hoveredElement = select(this); // Dispatch mouse event self.services.events.dispatchEvent( Events.Radar.X_AXIS_MOUSEOVER, { event, element: hoveredElement, datum, } ); const axisLine = self.parent.select( `.x-axes .x-axis-${Tools.kebabCase(datum)}` ); const dots = self.parent.selectAll( `.dots circle.${Tools.kebabCase(datum)}` ); // Change style axisLine .classed('hovered', true) .attr('stroke-dasharray', '4 4'); dots.classed('hovered', true) .attr('opacity', 1) .attr('r', Configuration.radar.dotsRadius); // get the items that should be highlighted const itemsToHighlight = self.fullDataNormalized.filter( (d) => d[angle] === datum ); const options = self.getOptions(); const { groupMapsTo } = options.data; const valueMapsTo = Tools.getProperty( options, 'radar', 'axes', 'value' ); // Show tooltip self.services.events.dispatchEvent(Events.Tooltip.SHOW, { event, hoveredElement, items: itemsToHighlight .filter( (datum) => typeof datum[valueMapsTo] === 'number' ) .map((datum) => ({ label: datum[groupMapsTo], value: datum[valueMapsTo], color: self.model.getFillColor(datum[groupMapsTo]), class: self.model.getColorClassName({ classNameTypes: [ColorClassNameTypes.TOOLTIP], dataGroupName: datum[groupMapsTo], }), })), }); }) .on('mousemove', function (event, datum) { const hoveredElement = select(this); // Dispatch mouse event self.services.events.dispatchEvent( Events.Radar.X_AXIS_MOUSEMOVE, { event, element: hoveredElement, datum, } ); self.services.events.dispatchEvent(Events.Tooltip.MOVE, { event, }); }) .on('click', function (event, datum) { // Dispatch mouse event self.services.events.dispatchEvent(Events.Radar.X_AXIS_CLICK, { event, element: select(this), datum, }); }) .on('mouseout', function (event, datum) { const hoveredElement = select(this); const axisLine = self.parent.select( `.x-axes .x-axis-${Tools.kebabCase(datum)}` ); const dots = self.parent.selectAll( `.dots circle.${Tools.kebabCase(datum)}` ); // Change style axisLine .classed('hovered', false) .attr('stroke-dasharray', '0'); dots.classed('hovered', false).attr('opacity', 0).attr('r', 0); // Dispatch mouse event self.services.events.dispatchEvent( Events.Radar.X_AXIS_MOUSEOUT, { event, element: hoveredElement, datum, } ); // Hide tooltip self.services.events.dispatchEvent(Events.Tooltip.HIDE); }); } }
the_stack
import { WheelChief } from '../utils/wheel_chief/wheel_chief' import { Commands112To113 } from './commands' import { Updater } from '../utils/wheel_chief/updater' import { escape, completeNamespace, isNumeric, getUuidLeastUuidMost, UpdateResult } from '../utils/utils' import { NbtCompound, NbtString, NbtShort, NbtInt, NbtByte, NbtLong, NbtList } from '../utils/nbt/nbt' import { UpdaterTo112 } from '../to112/updater' import { Selector113 as TargetSelector112 } from './utils/selector' import { TargetSelector as TargetSelector113 } from '../utils/selector' import Blocks from './mappings/blocks' import Items from './mappings/items' import ScoreboardCriterias from './mappings/scoreboard_criterias' import Effects from './mappings/effects' import Enchantments from './mappings/enchantments' import Particles from './mappings/particles' import Entities from './mappings/entities' import { SpuScriptExecutor112To113 } from './executor' import { ArgumentParser112To113 } from './parser' export class UpdaterTo113 extends Updater { public static upLine(input: string, from: string): UpdateResult { const ans: UpdateResult = { command: input, warnings: [] } if (['18', '19', '111'].indexOf(from) !== -1) { const result = UpdaterTo112.upLine(ans.command, from) ans.command = result.command ans.warnings = result.warnings } else if (from !== '112') { throw `Expected from version: '18', '19', '111' or '112' but got '${from}'.` } const result = new UpdaterTo113().upSpgodingCommand(ans.command) ans.command = result.command ans.warnings = ans.warnings.concat(result.warnings) return ans } public upArgument(input: string, updater: string) { switch (updater) { case 'spgoding:command_without_slash': return this.upSpgodingCommandWithoutSlash(input) case 'spgoding:difficulty': return this.upSpgodingDifficulty(input) case 'spgoding:effect': return this.upSpgodingEffect(input) case 'spgoding:enchantment': return this.upSpgodingEnchantment(input) case 'spgoding:gamemode': return this.upSpgodingGamemode(input) case 'spgoding:item_slot': return this.upSpgodingItemSlot(input) case 'spgoding:particle': return this.upSpgodingParticle(input) case 'spgoding:points_or_levels': return this.upSpgodingPointsOrLevels(input) case 'spgoding:pre_json': return this.upSpgodingPreJson(input) case 'spgoding:scoreboard_criteria': return this.upSpgodingScoreboardCriteria(input) case 'spgoding:single_selector': return this.upSpgodingSingleSelector(input) case 'spgoding:sound': return this.upSpgodingSound(input) case 'spgoding:to_literal_replace': return this.upSpgodingToLiteralReplace(input) default: return super.upArgument(input, updater) } } protected upMinecraftEntitySummon(input: string) { input = super.upMinecraftEntitySummon(input) input = Entities.to113(input) return input } protected upSpgodingBlockNbt(input: NbtCompound) { let ans = super.upSpgodingBlockNbt(input) /* CustomName */ { const customName = ans.get('CustomName') if (customName instanceof NbtString) { customName.set(this.upSpgodingPreJson(customName.get())) } } ans = Blocks.to113(Blocks.std112(undefined, undefined, undefined, undefined, input.toString())).getNbt() return ans } protected upSpgodingBlockParam(input: string) { return Blocks.to113(Blocks.std112(parseInt(input))).getFull() } protected upSpgodingCommand(input: string) { const result = WheelChief.update(input, Commands112To113.commands, new ArgumentParser112To113(), this, new SpuScriptExecutor112To113()) return { command: result.command, warnings: result.warnings } } protected upSpgodingCommandWithoutSlash(input: string) { const { command } = this.upSpgodingCommand(input) return command.charAt(0) === '/' ? command.slice(1) : command } protected upSpgodingDifficulty(input: string) { switch (input) { case '0': case 'p': case 'peaceful': return 'peaceful' case '1': case 'e': case 'easy': return 'easy' case '2': case 'n': case 'normal': return 'normal' case '3': case 'h': case 'hard': return 'hard' default: throw `Unknown difficulty: ${input}` } } protected upSpgodingEffect(input: string) { if (isNumeric(input)) { return Effects.to113(Number(input)) } else { return input } } protected upSpgodingEnchantment(input: string) { if (isNumeric(input)) { return Enchantments.to113(Number(input)) } else { return input } } protected upSpgodingEntityNbt(input: NbtCompound) { const ans = super.upSpgodingEntityNbt(input) /* carried & carriedData */ { const carried = ans.get('carried') const carriedData = ans.get('carriedData') ans.del('carried') ans.del('carriedData') if ( (carried instanceof NbtString) && (carriedData instanceof NbtShort || carriedData instanceof NbtInt || typeof carriedData === 'undefined') ) { const carriedBlockState = Blocks.upStringToBlockState(carried, carriedData) ans.set('carriedBlockState', carriedBlockState) } else if ( (carried instanceof NbtShort || carried instanceof NbtInt) && (carriedData instanceof NbtShort || carriedData instanceof NbtInt || typeof carriedData === 'undefined') ) { const carriedBlockState = this.upBlockNumericIDToBlockState(carried, carriedData) ans.set('carriedBlockState', carriedBlockState) } } /* inTile */ { const inTile = ans.get('inTile') ans.del('inTile') if (inTile instanceof NbtString) { const inBlockState = Blocks.upStringToBlockState(inTile) ans.set('inBlockState', inBlockState) } } /* Block & Data & TileEntityData */ { const block = ans.get('Block') const data = ans.get('Data') ans.del('Block') ans.del('Data') if ( block instanceof NbtString && (data instanceof NbtByte || data instanceof NbtInt || typeof data === 'undefined') ) { const blockState = Blocks.upStringToBlockState(block, data) ans.set('BlockState', blockState) } let tileEntityData = ans.get('TileEntityData') if ( block instanceof NbtString && tileEntityData instanceof NbtCompound && (data instanceof NbtInt || data instanceof NbtByte || data === undefined) ) { tileEntityData = Blocks.to113( Blocks.std112(undefined, block.get(), data ? data.get() : 0, undefined, tileEntityData.toString()) ).getNbt() ans.set('TileEntityData', tileEntityData) } } /* DisplayTile & DisplayData */ { const displayTile = ans.get('DisplayTile') const displayData = ans.get('DisplayData') ans.del('DisplayTile') ans.del('DisplayData') if ( displayTile instanceof NbtString && (displayData instanceof NbtInt || typeof displayData === 'undefined') ) { const displayState = Blocks.upStringToBlockState(displayTile, displayData) ans.set('DisplayState', displayState) } } /* Particle & ParticleParam1 & ParticleParam2 */ { const particle = ans.get('Particle') const particleParam1 = ans.get('ParticleParam1') const particleParam2 = ans.get('ParticleParam2') ans.del('ParticleParam1') ans.del('ParticleParam2') if (particle instanceof NbtString) { particle.set(this.upSpgodingParticle(particle.get())) if (particle.get() === 'block') { if (particleParam1 instanceof NbtInt) { particle.set(particle.get() + ' ' + this.upSpgodingBlockParam(particleParam1.get().toString())) } } else if (particle.get() === 'item') { if (particleParam1 instanceof NbtInt && particleParam2 instanceof NbtInt) { particle.set( particle.get() + ' ' + this.upSpgodingItemParams( particleParam1.get().toString() + ' ' + particleParam2.get().toString() ) ) } } } } /* Owner */ { let owner = ans.get('Owner') ans.del('Owner') if (owner instanceof NbtString) { const uuid = getUuidLeastUuidMost(owner.get()) const m = new NbtLong(uuid.M) const l = new NbtLong(uuid.L) owner = new NbtCompound() owner.set('M', m) owner.set('L', l) ans.set('Owner', owner) } } /* owner */ { let owner = ans.get('owner') ans.del('owner') if (owner instanceof NbtString) { const uuid = getUuidLeastUuidMost(owner.get()) const m = new NbtLong(uuid.M) const l = new NbtLong(uuid.L) owner = new NbtCompound() owner.set('M', m) owner.set('L', l) ans.set('owner', owner) } } /* Thrower */ { let thrower = ans.get('Thrower') ans.del('Thrower') if (thrower instanceof NbtString) { const uuid = getUuidLeastUuidMost(thrower.get()) const m = new NbtLong(uuid.M) const l = new NbtLong(uuid.L) thrower = new NbtCompound() thrower.set('M', m) thrower.set('L', l) ans.set('Thrower', thrower) } } /* CustomName */{ const customName = ans.get('CustomName') if (customName instanceof NbtString) { customName.set(this.upSpgodingPreJson(customName.get())) } return ans } } private upBlockNumericIDToBlockState(id: NbtShort | NbtInt, data?: NbtShort | NbtInt) { const blockState = new NbtCompound() const name = new NbtString() const properties = new NbtCompound() const metadata = data ? data.get() : 0 const std = Blocks.to113(Blocks.std112(id.get(), undefined, metadata)) name.set(std.getName()) if (std.hasStates()) { std.getStates().forEach(v => { const val = new NbtString() const pairs = v.split('=') val.set(pairs[1]) properties.set(pairs[0], val) }) blockState.set('Properties', properties) } blockState.set('Name', name) return blockState } public upSpgodingGamemode(input: string) { switch (input) { case '0': case 's': case 'survival': return 'survival' case '1': case 'c': case 'creative': return 'creative' case '2': case 'a': case 'adventure': return 'adventure' case '3': case 'sp': case 'spectator': return 'spectator' default: throw `Unknown gamemode: ${input}` } } protected upSpgodingItemNbt(input: NbtCompound): NbtCompound { input = super.upSpgodingItemNbt(input) const result = Items.to113(Items.std112(undefined, undefined, undefined, undefined, input.toString())) input = result.getNbt() return input } protected upSpgodingItemTagNbt(input: NbtCompound) { input = super.upSpgodingItemTagNbt(input) /* ench */ { const enchantments = input.get('ench') input.del('ench') if (enchantments instanceof NbtList) { for (let i = 0; i < enchantments.length; i++) { const enchantment = enchantments.get(i) if (enchantment instanceof NbtCompound) { let id = enchantment.get('id') if (id instanceof NbtShort || id instanceof NbtInt) { const strID = Enchantments.to113(id.get()) id = new NbtString() id.set(strID) enchantment.set('id', id) } enchantments.set(i, enchantment) } } input.set('Enchantments', enchantments) } } /* StoredEnchantments */ { const storedEnchantments = input.get('StoredEnchantments') if (storedEnchantments instanceof NbtList) { for (let i = 0; i < storedEnchantments.length; i++) { const enchantment = storedEnchantments.get(i) if (enchantment instanceof NbtCompound) { let id = enchantment.get('id') if (id instanceof NbtShort || id instanceof NbtInt) { const strID = Enchantments.to113(id.get()) id = new NbtString() id.set(strID) enchantment.set('id', id) } storedEnchantments.set(i, enchantment) } } input.set('StoredEnchantments', storedEnchantments) } } /* display.(Name|LocName) */ { const display = input.get('display') if (display instanceof NbtCompound) { const name = display.get('Name') if (name instanceof NbtString) { name.set(`{"text":"${escape(name.get())}"}`) display.set('Name', name) } const locName = display.get('LocName') display.del('LocName') if (locName instanceof NbtString) { locName.set(`{"translate":"${locName.get()}"}`) display.set('Name', locName) } input.set('display', display) } } return input } protected upSpgodingItemParams(input: string) { return Items.to113(Items.std112(parseInt(input.split(' ')[0]), undefined, parseInt(input.split(' ')[1]))).getNominal() } protected upSpgodingItemSlot(input: string) { return input.slice(5) } protected upSpgodingTargetSelector(input: string) { const sel = new TargetSelector112() sel.parse(input) const ans = sel.to113() return ans } protected upSpgodingParticle(input: string) { return Particles.to113(input) } protected upSpgodingPointsOrLevels(input: string) { if (input.slice(-1).toUpperCase() === 'L') { return `${input.slice(0, -1)} levels` } else { return `${input} points` } } protected upSpgodingPreJson(input: string) { return `{"text":"${escape(input)}"}` } protected upSpgodingScoreboardCriteria(input: string) { if (input.slice(0, 5) === 'stat.') { const subs = input.split(/\./g) const newCrit = ScoreboardCriterias.to113(subs[1]) switch (subs[1]) { case 'mineBlock': let block = '' if (isNumeric(subs[2])) { block = Blocks.to113(Blocks.std112(Number(subs[2]))) .getName() .replace(/:/g, '.') .replace(/\[.*$/g, '') } else { block = Blocks.to113(Blocks.std112(undefined, `${subs[2]}:${subs[3]}`)) .getName() .replace(/:/g, '.') .replace(/\[.*$/g, '') } return `minecraft.${newCrit}:${block}` case 'craftItem': case 'useItem': case 'breakItem': case 'pickup': case 'drop': let item = '' if (isNumeric(subs[2])) { item = Items.to113(Items.std112(Number(subs[2]))) .getName() .replace(/:/g, '.') .replace(/\[.*$/g, '') } else { item = Items.to113(Items.std112(undefined, `${subs[2]}:${subs[3]}`)) .getName() .replace(/:/g, '.') .replace(/\[.*$/g, '') } return `minecraft.${newCrit}:${item}` case 'killEntity': case 'entityKilledBy': const entity = Entities.to113(Entities.to112(subs[2])).replace(/:/g, '.') return `minecraft.${newCrit}:${entity}` default: return `minecraft.custom:minecraft.${subs[1]}` } } else { return input } } protected upSpgodingSingleSelector(input: string) { const sel112 = new TargetSelector112() sel112.parse(input) const sel113 = new TargetSelector113(sel112.to113()) if (sel113.limit !== undefined || sel113.variable === 'a' || sel113.variable === 'e') { sel113.limit = '1' } return sel113.toString() } protected upSpgodingSound(input: string) { input = completeNamespace(input) .replace('minecraft:entity.endermen', 'minecraft:entity.enderman') .replace('minecraft:entity.enderdragon', 'minecraft:entity.ender_dragon') return input } protected upSpgodingToLiteralReplace(input: string) { if (['replace', 'keep', 'destroy'].indexOf(input) !== -1) { return input } else { return 'replace' } } }
the_stack
import * as React from 'react' import * as Constants from '../../constants/provision' import * as Kb from '../../common-adapters' import * as Styles from '../../styles' import * as Flow from '../../util/flow' import QRImage from './qr-image' import QRScan from './qr-scan/container' import {isAndroid} from '../../constants/platform' import Troubleshooting from '../troubleshooting' import * as Types from '../../constants/types/provision' import * as DeviceTypes from '../../constants/types/devices' export type DeviceType = 'mobile' | 'desktop' export type Tab = 'QR' | 'enterText' | 'viewText' const currentDeviceType: DeviceType = Styles.isMobile ? 'mobile' : 'desktop' type Props = { error: string currentDevice: DeviceTypes.Device currentDeviceAlreadyProvisioned: boolean currentDeviceName: string iconNumber: number otherDevice: Types.Device tabOverride?: Tab textCode: string onBack: () => void onClose: () => void onSubmitTextCode: (code: string) => void waiting: boolean } type State = { code: string tab: Tab troubleshooting: boolean } class CodePage2 extends React.Component<Props, State> { static navigationOptions = { header: null, headerBottomStyle: {height: undefined}, headerLeft: null, headerTransparent: true, } constructor(props: Props) { super(props) this.state = { code: '', tab: (__STORYBOOK__ && this.props.tabOverride) || this._defaultTab(this.props), troubleshooting: false, } } componentDidUpdate(prevProps: Props) { const curDefault = this._defaultTab(this.props) const prevDefault = this._defaultTab(prevProps) if (curDefault !== prevDefault) { this.setState({tab: curDefault}) } } componentWillUnmount() { // Troubleshooting modal may send us back to the devices page; it already cancels in that case !this.state.troubleshooting && this.props.onClose() } static _validTabs = (deviceType: DeviceType, otherDeviceType) => { if (deviceType === 'desktop' && otherDeviceType === 'desktop') { return ['viewText', 'enterText'] } else { return ['QR', 'viewText', 'enterText'] } } _defaultTab = (props: Props) => { const oppositeTabMap = { QR: 'QR', enterText: 'viewText', viewText: 'enterText', } const getTabOrOpposite = tabToShowToNew => props.currentDeviceAlreadyProvisioned ? oppositeTabMap[tabToShowToNew] : tabToShowToNew if (currentDeviceType === 'mobile') { return getTabOrOpposite('QR') } else if (currentDeviceType === 'desktop') { return props.otherDevice.type === 'desktop' ? getTabOrOpposite('viewText') : getTabOrOpposite('QR') } throw new Error('Impossible defaultTab') } _tabBackground = () => (this.state.tab === 'QR' ? Styles.globalColors.blueLight : Styles.globalColors.green) _buttonBackground = () => (this.state.tab === 'QR' ? 'blue' : 'green') _setCode = (code: string) => this.setState(s => (s.code === code ? null : {code})) _onSubmitTextCode = () => this.props.onSubmitTextCode(this.state.code) _header = () => { return Styles.isMobile ? { leftButton: ( <Kb.Text type="BodyBig" onClick={this.props.onBack} negative={true}> {this.props.currentDeviceAlreadyProvisioned ? 'Back' : 'Cancel'} </Kb.Text> ), style: {backgroundColor: this._tabBackground()}, } : undefined } _body = () => { let content: React.ReactNode = null switch (this.state.tab) { case 'QR': content = <Qr {...this.props} /> break case 'viewText': content = <ViewText {...this.props} /> break case 'enterText': content = <EnterText {...this.props} code={this.state.code} setCode={this._setCode} /> break default: Flow.ifFlowComplainsAboutThisFunctionYouHaventHandledAllCasesInASwitch(this.state.tab) } return ( <Kb.Box2 direction="vertical" fullWidth={true} style={Styles.collapseStyles([styles.codePageContainer, {backgroundColor: this._tabBackground()}])} > <Kb.Box2 direction="vertical" fullHeight={true} style={ this.props.currentDeviceAlreadyProvisioned ? styles.imageContainerOnLeft : styles.imageContainerOnRight } > <Kb.Icon type={ this.state.tab === 'QR' ? 'illustration-bg-provisioning-blue' : 'illustration-bg-provisioning-green' } style={ this.props.currentDeviceAlreadyProvisioned ? styles.backgroundOnLeft : styles.backgroundOnRight } /> </Kb.Box2> {!this.props.currentDeviceAlreadyProvisioned && !Styles.isMobile && ( <> <Kb.BackButton onClick={this.props.onBack} iconColor={Styles.globalColors.white} style={styles.backButton} textStyle={styles.backButtonText} /> <Kb.Divider /> </> )} {!!this.props.error && <Kb.Banner color="red">{this.props.error}</Kb.Banner>} <Kb.Box2 direction="vertical" fullWidth={true} style={styles.scrollContainer}> <Kb.Box2 direction="vertical" fullHeight={true} style={Styles.globalStyles.flexGrow}> <Kb.Box2 direction="vertical" style={styles.container} fullWidth={true} gap="tiny"> <Instructions {...this.props} /> {content} <SwitchTab {...this.props} selected={this.state.tab} onSelect={tab => this.setState({tab})} /> {!this._inModal() && this._footer().content} </Kb.Box2> </Kb.Box2> </Kb.Box2> {!this._inModal() && currentDeviceType === 'desktop' && currentDeviceType === this.props.otherDevice.type && !this.props.currentDeviceAlreadyProvisioned && this._heyWaitBanner()} {!this._inModal() && this.state.troubleshooting && ( <Kb.Overlay onHidden={() => this.setState({troubleshooting: false})} propagateOutsideClicks={true}> {this._troubleshooting()} </Kb.Overlay> )} </Kb.Box2> ) } _footer = () => { const showHeyWaitInFooter = currentDeviceType === 'mobile' && currentDeviceType === this.props.otherDevice.type && !this.props.currentDeviceAlreadyProvisioned return { content: ( <Kb.Box2 alignItems="center" direction="vertical" gap={Styles.isMobile ? 'medium' : 'small'} gapEnd={!showHeyWaitInFooter} fullWidth={true} > {this.state.tab === 'enterText' && ( <Kb.WaitingButton fullWidth={true} backgroundColor={this._buttonBackground()} label="Continue" onClick={this._onSubmitTextCode} disabled={!this.state.code || this.props.waiting} style={styles.enterTextButton} waitingKey={Constants.waitingKey} /> )} {this.state.tab !== 'enterText' && this._inModal() && !Styles.isMobile && ( <Kb.WaitingButton fullWidth={true} backgroundColor={this._buttonBackground()} label="Close" onClick={this.props.onBack} onlyDisable={true} style={styles.closeButton} waitingKey={Constants.waitingKey} /> )} {showHeyWaitInFooter && this._heyWaitBanner()} </Kb.Box2> ), hideBorder: !this._inModal() || currentDeviceType !== 'desktop', style: {backgroundColor: this._tabBackground(), ...Styles.padding(Styles.globalMargins.xsmall, 0, 0)}, } } _heyWaitBanner = () => ( <Kb.ClickableBox onClick={() => this.setState({troubleshooting: true})}> <Kb.Banner color="yellow"> <Kb.BannerParagraph bannerColor="yellow" content={[ `Are you on that ${this.props.otherDevice.type === 'mobile' ? 'phone' : 'computer'} now? `, {onClick: () => this.setState({troubleshooting: true}), text: 'Resolve'}, ]} /> </Kb.Banner> </Kb.ClickableBox> ) _troubleshooting = () => ( <Troubleshooting mode={this.state.tab === 'QR' ? 'QR' : 'text'} onCancel={() => this.setState({troubleshooting: false})} otherDeviceType={this.props.otherDevice.type} /> ) // We're in a modal unless this is a desktop being newly provisioned. _inModal = () => currentDeviceType !== 'desktop' || this.props.currentDeviceAlreadyProvisioned render() { // Workaround for no modals while logged out: display just the troubleshooting modal if we're on mobile and it's open; // When we're on desktop being newly provisioned, it's in this._body() if (Styles.isMobile && this.state.troubleshooting) { return this._troubleshooting() } const content = this._body() if (this._inModal()) { return ( <Kb.Modal header={this._header()} footer={this._footer()} onClose={this.props.onBack} mode="Wide" mobileStyle={{backgroundColor: this._tabBackground()}} > {content} </Kb.Modal> ) } return content } } const textType = 'BodySemibold' const SwitchTab = ( props: { selected: Tab onSelect: (tab: Tab) => void } & Props ) => { if (currentDeviceType === 'desktop' && props.otherDevice.type === 'desktop') { return null } let label let tab if (props.selected === 'QR') { label = 'Type secret instead' if (currentDeviceType === 'mobile' && props.otherDevice.type === 'mobile') { tab = (props.currentDeviceAlreadyProvisioned ? Styles.isMobile : !Styles.isMobile) ? 'viewText' : 'enterText' } else if (currentDeviceType === 'mobile') { tab = 'viewText' } else { tab = 'enterText' } } else { label = 'Scan QR instead' tab = 'QR' } return ( <Kb.Box2 direction="horizontal" gap="xtiny" style={styles.switchTabContainer}> <Kb.Text type="BodySmallPrimaryLink" negative={true} onClick={() => props.onSelect(tab)} style={styles.switchTab} > {label} </Kb.Text> </Kb.Box2> ) } const Qr = (props: Props) => currentDeviceType === 'desktop' ? ( <Kb.Box2 direction="vertical" style={styles.qrOnlyContainer}> <QRImage code={props.textCode} cellSize={8} /> </Kb.Box2> ) : ( <Kb.Box2 style={Styles.collapseStyles([ styles.qrContainer, props.currentDeviceAlreadyProvisioned && styles.qrContainerFlip, ])} direction="vertical" > <Kb.Box2 direction="vertical" style={styles.qrImageContainer}> <QRImage code={props.textCode} /> </Kb.Box2> <QRScan /> </Kb.Box2> ) const EnterText = (props: Props & {code: string; setCode: (code: string) => void}) => { const {code, setCode} = props const {onSubmitTextCode} = props const onSubmit = React.useCallback( e => { e.preventDefault() code && onSubmitTextCode(code) }, [code, onSubmitTextCode] ) return ( <Kb.Box2 direction="vertical" style={styles.enterTextContainer} gap="small"> <Kb.PlainInput autoFocus={true} multiline={true} onChangeText={setCode} onEnterKeyDown={onSubmit} rowsMin={3} placeholder={`Type the ${props.otherDevice.type === 'mobile' ? '9' : '8'}-word secret code`} textType="Terminal" style={styles.enterTextInput} value={code} /> </Kb.Box2> ) } const ViewText = (props: Props) => ( <Kb.Box2 direction="vertical" style={styles.viewTextContainer}> <Kb.Text center={true} type="Terminal" style={styles.viewTextCode}> {props.textCode} </Kb.Text> </Kb.Box2> ) const Instructions = (p: Props) => { const maybeIcon = ({ desktop: `icon-computer-background-${p.iconNumber}-96`, mobile: `icon-phone-background-${p.iconNumber}-96`, } as const)[p.currentDeviceAlreadyProvisioned ? p.currentDevice.type : p.otherDevice.type] const icon = Kb.isValidIconType(maybeIcon) ? maybeIcon : 'icon-computer-96' return ( <Kb.Box2 direction="vertical"> {p.currentDeviceAlreadyProvisioned ? ( <Kb.Box2 alignItems="center" direction="horizontal" style={styles.flexWrap}> <Kb.Text type={textType} style={styles.instructions}> Ready to authorize using </Kb.Text> <Kb.Icon type={icon} sizeType="Default" style={Styles.collapseStyles([ styles.deviceIcon, p.currentDevice.type === 'desktop' && styles.deviceIconDesktop, p.currentDevice.type === 'mobile' && styles.deviceIconMobile, ])} /> <Kb.Text type={textType} style={styles.instructions}> {p.currentDeviceName}. </Kb.Text> </Kb.Box2> ) : ( <> <Kb.Box2 alignItems="flex-end" direction="horizontal" gap="xtiny"> <Kb.Text type={textType} style={Styles.collapseStyles([styles.instructions, styles.instructionsUpper])} > On </Kb.Text> <Kb.Icon type={icon} sizeType="Default" style={Styles.collapseStyles([ styles.deviceIcon, p.otherDevice.type === 'desktop' && styles.deviceIconDesktop, p.otherDevice.type === 'mobile' && styles.deviceIconMobile, ])} /> <Kb.Text type={textType} style={Styles.collapseStyles([styles.instructions, styles.instructionsUpper])} > {p.otherDevice.name}, go to {p.otherDevice.type === 'desktop' && 'Devices'} </Kb.Text> </Kb.Box2> {p.otherDevice.type === 'mobile' && ( <Kb.Box2 alignItems="center" direction="horizontal" centerChildren={true} gap="xtiny" style={Styles.globalStyles.flexWrap} > {p.otherDevice.type === 'mobile' && ( <> <Kb.Icon type="iconfont-nav-2-hamburger" color={Styles.globalColors.white} sizeType="Default" style={styles.hamburger} /> <Kb.Icon type="iconfont-arrow-right" color={Styles.globalColors.white} sizeType="Tiny" /> </> )} <Kb.Text type={textType} style={styles.instructions}> Devices </Kb.Text> </Kb.Box2> )} <Kb.Text type={textType} style={styles.instructionsContainer} center={true}> <Kb.Text type={textType} style={Styles.collapseStyles([styles.instructions, styles.instructionsUpper])} > and authorize a new phone. </Kb.Text> </Kb.Text> </> )} </Kb.Box2> ) } const styles = Styles.styleSheetCreate( () => ({ backButton: Styles.platformStyles({ isElectron: { alignSelf: 'flex-start', marginTop: 56, // we're under the header, need to shift down paddingBottom: Styles.globalMargins.small, paddingLeft: Styles.globalMargins.xsmall, position: 'relative', // otherwise the absolutely positioned background makes this unclickable zIndex: undefined, // annoyingly this is set inside Kb.BackButton }, isMobile: { marginBottom: 0, marginLeft: 0, marginTop: 0, }, }), backButtonText: { color: Styles.globalColors.white, }, backgroundOnLeft: { marginLeft: -230, }, backgroundOnRight: { marginRight: -230, }, closeButton: { marginLeft: Styles.globalMargins.small, marginRight: Styles.globalMargins.small, }, codePageContainer: Styles.platformStyles({ common: { flex: 1, overflow: 'hidden', position: 'relative', }, }), container: Styles.platformStyles({ common: { justifyContent: 'space-between', }, isElectron: { height: '100%', padding: Styles.globalMargins.large, }, isMobile: { flexGrow: 1, paddingBottom: Styles.globalMargins.small, paddingLeft: Styles.globalMargins.small, paddingRight: Styles.globalMargins.small, paddingTop: Styles.globalMargins.small, }, }), deviceIcon: { height: 32, width: 32, }, deviceIconDesktop: { marginLeft: Styles.globalMargins.xtiny, marginRight: Styles.globalMargins.xxtiny, }, deviceIconMobile: { marginLeft: Styles.globalMargins.xxtiny, marginRight: 0, }, enterTextButton: { marginLeft: Styles.globalMargins.small, marginRight: Styles.globalMargins.small, maxWidth: Styles.isMobile ? undefined : 460, width: '90%', }, enterTextContainer: { alignItems: Styles.isMobile ? 'stretch' : 'center', alignSelf: 'stretch', }, enterTextInput: Styles.platformStyles({ common: { ...Styles.globalStyles.fontTerminalSemibold, backgroundColor: Styles.globalColors.white, borderRadius: 4, color: Styles.globalColors.greenDark, paddingBottom: 15, paddingLeft: 20, paddingRight: 20, paddingTop: 15, }, isElectron: { fontSize: 16, maxWidth: 460, }, isMobile: { width: '100%', }, }), flexWrap: Styles.platformStyles({isMobile: {flexWrap: 'wrap'}}), hamburger: Styles.platformStyles({ isMobile: { bottom: 1, marginRight: Styles.globalMargins.xtiny, position: 'relative', right: 1, }, }), imageContainerOnLeft: { ...Styles.globalStyles.fillAbsolute, ...Styles.globalStyles.flexBoxColumn, alignItems: 'flex-start', justifyContent: 'center', }, imageContainerOnRight: { ...Styles.globalStyles.fillAbsolute, ...Styles.globalStyles.flexBoxColumn, alignItems: 'flex-end', justifyContent: 'center', }, instructions: { color: Styles.globalColors.white, }, instructionsContainer: { padding: Styles.globalMargins.tiny, }, instructionsUpper: { marginBottom: Styles.globalMargins.tiny, }, qrContainer: Styles.platformStyles({ common: { // MUST be white, else darkmode messes up the qr code backgroundColor: Styles.globalColors.whiteOrWhite, borderRadius: isAndroid ? 0 : 8, // If this is set to ANYTHING other than 0 android DOESN"T WORK!!!!!! The qr scanner totally breaks flexDirection: 'column', padding: 4, }, isElectron: { width: 220, }, isMobile: { width: 160, }, }), qrContainerFlip: { flexDirection: 'column-reverse', }, qrImageContainer: { paddingBottom: 10, paddingTop: 10, }, qrOnlyContainer: { backgroundColor: Styles.globalColors.whiteOrWhite, borderRadius: 8, padding: 20, }, scrollContainer: { flexGrow: 1, position: 'relative', }, switchTab: { marginBottom: Styles.globalMargins.xtiny, marginTop: Styles.globalMargins.tiny, }, switchTabContainer: { alignItems: 'center', }, viewTextCode: Styles.platformStyles({ common: { ...Styles.globalStyles.fontTerminalSemibold, color: Styles.globalColors.greenLight, fontSize: 16, }, isElectron: { maxWidth: 330, }, }), viewTextContainer: Styles.platformStyles({ common: { backgroundColor: Styles.globalColors.greenDark, borderRadius: 4, }, isElectron: { alignItems: 'center', maxWidth: 460, paddingBottom: 20, paddingLeft: 64, paddingRight: 64, paddingTop: 20, }, isMobile: { alignItems: 'center', alignSelf: 'stretch', paddingBottom: 20, paddingLeft: 20, paddingRight: 20, paddingTop: 20, }, }), } as const) ) export default CodePage2
the_stack
import { Diagram } from '../diagram'; import { NodeModel } from './../objects/node-model'; import { Node } from './../objects/node'; import { ConnectorModel } from './../objects/connector-model'; import { NodeConstraints, ConnectorConstraints, DiagramConstraints, DiagramTools, DiagramAction, RendererAction } from '../enum/enum'; import { AnnotationConstraints, PortConstraints } from '../enum/enum'; import { Connector } from './../objects/connector'; import { AnnotationModel, PathAnnotationModel, ShapeAnnotationModel } from './../objects/annotation-model'; import { PointPortModel } from './../objects/port-model'; import { Selector } from './../objects/node'; import { SelectorModel } from './../objects/node-model'; import { ShapeAnnotation, PathAnnotation } from '../objects/annotation'; /** * constraints-util module contains the common constraints \ * * @returns { number } constraints-util module contains the common constraints .\ * * @param {ConnectorModel | NodeModel | PathAnnotationModel | ShapeAnnotationModel} node - Provide the DiagramElement value. * @private */ export function canSelect(node: ConnectorModel | NodeModel | PathAnnotationModel | ShapeAnnotationModel): number { if (node) { let state: number = 0; if ((node instanceof ShapeAnnotation) || (node instanceof PathAnnotation)) { state = node.constraints & AnnotationConstraints.Select; } else if (node instanceof Connector) { state = node.constraints & ConnectorConstraints.Select; } else { state = node.constraints & NodeConstraints.Select; } return state; } return 1; } /** * Used to check whether we can move the objects ot not\ * * @returns { number } Used to check whether we can move the objects ot not .\ * * @param {ConnectorModel | NodeModel | PathAnnotationModel | ShapeAnnotationModel} node - Used to check whether we can move the objects ot not. * @private */ export function canMove(node: ConnectorModel | NodeModel | SelectorModel | ShapeAnnotationModel | PathAnnotationModel): number { if (node) { let state: number = 0; if ((node instanceof ShapeAnnotation) || (node instanceof PathAnnotation)) { state = node.constraints & AnnotationConstraints.Drag; } else if (node instanceof Connector) { state = node.constraints & ConnectorConstraints.Drag; } else if (node instanceof Selector) { state = 1; } else { state = node.constraints & NodeConstraints.Drag; } return state; } return 1; } /** * Used to check the canEnablePointerEvents\ * * @returns { number } Used to check whether we can move the objects ot not .\ * * @param {ConnectorModel | NodeModel} node - Used to check whether we can move the objects ot not. * @param {Diagram} diagram - Used to check whether we can move the objects ot not. * @private */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export function canEnablePointerEvents(node: ConnectorModel | NodeModel, diagram: Diagram): number { let state: number = 0; if (node instanceof Connector) { state = node.constraints & ConnectorConstraints.PointerEvents; } else { state = node.constraints & NodeConstraints.PointerEvents; } return state; } /** * Used to check the canDelete of the element \ * * @returns { number } Used to check the canDelete of the element .\ * * @param {ConnectorModel | NodeModel} node - Used to check whether we can move the objects ot not. * @private */ export function canDelete(node: ConnectorModel | NodeModel): number { let state: number = 0; if (node instanceof Connector) { state = node.constraints & ConnectorConstraints.Delete; } else { state = node.constraints & NodeConstraints.Delete; } return state; } /** * Used to check the bridging of the element \ * * @returns { number } Used to check the bridging of the element .\ * * @param {ConnectorModel | NodeModel} connector - provide the connector value. * @param {ConnectorModel | NodeModel} diagram - provide the diagram value. * @private */ export function canBridge(connector: Connector, diagram: Diagram): number { let state: number = 0; if (connector.constraints & ConnectorConstraints.Bridging) { state = connector.constraints & ConnectorConstraints.Bridging; } else if (connector.constraints & ConnectorConstraints.InheritBridging) { state = diagram.constraints & DiagramConstraints.Bridging; } else { state = 0; } return state; } /** * Used to check the routing of the element \ * * @returns { number } Used to check the routing of the element .\ * * @param {ConnectorModel | NodeModel} connector - provide the connector value. * @param {ConnectorModel | NodeModel} diagram - provide the diagram value. * @private */ export function canEnableRouting(connector: Connector, diagram: Diagram): number { let state: number = 0; if (connector.constraints & ConnectorConstraints.LineRouting) { state = connector.constraints & ConnectorConstraints.LineRouting; } else if (connector.constraints & ConnectorConstraints.InheritLineRouting) { state = diagram.constraints & DiagramConstraints.LineRouting; } return state; } /** * Used to check the source end dragof the element \ * * @returns { number } Used to check the source end dragof the element. \ * * @param {ConnectorModel | NodeModel} connector - provide the connector value. * @private */ export function canDragSourceEnd(connector: Connector): number { return connector.constraints & ConnectorConstraints.DragSourceEnd; } /** * Used to check the target end drag of the element \ * * @returns { number } Used to check the target end drag of the element .\ * * @param {ConnectorModel | NodeModel} connector - provide the connector value. * @private */ export function canDragTargetEnd(connector: Connector): number { return connector.constraints & ConnectorConstraints.DragTargetEnd; } /** * Used to check the segment drag of the element \ * * @returns { number } Used to check the segment drag of the element .\ * * @param {ConnectorModel | NodeModel} connector - provide the connector value. * @private */ export function canDragSegmentThumb(connector: Connector): number { return connector.constraints & ConnectorConstraints.DragSegmentThumb; } /** * Used to check the routing drag of the element \ * * @returns { number } Used to check the segment drag of the element .\ * * @param {NodeModel | ShapeAnnotationModel | PathAnnotationModel} node - provide the connector value. * @private */ export function canRotate(node: NodeModel | ShapeAnnotationModel | PathAnnotationModel): number { if ((node instanceof ShapeAnnotation) || (node instanceof PathAnnotation)) { return node.constraints & AnnotationConstraints.Rotate; } else { return node.constraints & NodeConstraints.Rotate; } } /** * Used to check shadown constraints of the element \ * * @returns { number } Used to check shadown constraints of the element .\ * * @param {NodeModel} node - provide the connector value. * @private */ export function canShadow(node: NodeModel): number { return node.constraints & NodeConstraints.Shadow; } /** * Used to check canInConnect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {NodeModel} node - provide the node value. * @private */ export function canInConnect(node: NodeModel): number { if ((node instanceof Node) && (node.constraints & NodeConstraints.InConnect)) { return node.constraints & NodeConstraints.InConnect; } return 0; } /** * Used to check canPortInConnect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {PointPortModel} port - provide the PointPortModel value. * @private */ export function canPortInConnect(port: PointPortModel): number { if (port && port.constraints) { if (!(port.constraints & PortConstraints.None) && (port.constraints & PortConstraints.InConnect)) { return port.constraints & PortConstraints.InConnect; } } return 0; } /** * Used to check canOutConnect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {NodeModel} node - provide the node value. * @private */ export function canOutConnect(node: NodeModel): number { if ((node instanceof Node) && (node.constraints & NodeConstraints.OutConnect)) { return node.constraints & NodeConstraints.OutConnect; } return 0; } /** * Used to check canPortOutConnect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {PointPortModel} port - provide the node value. * @private */ export function canPortOutConnect(port: PointPortModel): number { if (port && port.constraints) { if (!(port.constraints & PortConstraints.None) && (port.constraints & PortConstraints.OutConnect)) { return port.constraints & PortConstraints.OutConnect; } } return 0; } /** * Used to check canResize constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {NodeModel | ShapeAnnotationModel | PathAnnotationModel} node - provide the node value. * @param {NodeModel | ShapeAnnotationModel | PathAnnotationModel} direction - provide the node value. * @private */ export function canResize(node: NodeModel | ShapeAnnotationModel | PathAnnotationModel, direction?: string): number { let returnValue: number = 0; if (node instanceof ShapeAnnotation || node instanceof PathAnnotation) { returnValue = node.constraints & AnnotationConstraints.Resize; } else if (node) { if (direction === 'SouthEast') { returnValue = node.constraints & NodeConstraints.ResizeSouthEast; } else if (direction === 'East') { returnValue = node.constraints & NodeConstraints.ResizeEast; } else if (direction === 'NorthEast') { returnValue = node.constraints & NodeConstraints.ResizeNorthEast; } else if (direction === 'South') { returnValue = node.constraints & NodeConstraints.ResizeSouth; } else if (direction === 'North') { returnValue = node.constraints & NodeConstraints.ResizeNorth; } else if (direction === 'SouthWest') { returnValue = node.constraints & NodeConstraints.ResizeSouthWest; } else if (direction === 'West') { returnValue = node.constraints & NodeConstraints.ResizeWest; } else if (direction === 'NorthWest') { returnValue = node.constraints & NodeConstraints.ResizeNorthWest; } } return returnValue; } /** * Used to check canAllowDrop constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {ConnectorModel | NodeModel} node - provide the node value. * @private */ export function canAllowDrop(node: ConnectorModel | NodeModel): number { let state: number = 0; if (node instanceof Connector) { state = node.constraints & ConnectorConstraints.AllowDrop; } else { state = node.constraints & NodeConstraints.AllowDrop; } return state; } /** * Used to check canVitualize constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} diagram - provide the Diagram value. * @private */ export function canVitualize(diagram: Diagram): number { return diagram.constraints & DiagramConstraints.Virtualization; } /** * Used to check canEnableToolTip constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {ConnectorModel | NodeModel} node - provide the node value. * @param {Diagram} diagram - provide the Diagram value. * @private */ export function canEnableToolTip(node: ConnectorModel | NodeModel, diagram: Diagram): number { let state: number = 0; if (node instanceof Connector) { if (node.constraints & ConnectorConstraints.Tooltip) { state = node.constraints & ConnectorConstraints.Tooltip; } else if (node.constraints & ConnectorConstraints.InheritTooltip) { state = diagram.constraints & DiagramConstraints.Tooltip; } } else { if (node.constraints & NodeConstraints.Tooltip) { state = node.constraints & NodeConstraints.Tooltip; } else if (node.constraints & NodeConstraints.InheritTooltip) { state = diagram.constraints & DiagramConstraints.Tooltip; } } return state; } /** * Used to check canSingleSelect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canSingleSelect(model: Diagram): number { return model.tool & DiagramTools.SingleSelect; } /** * Used to check canMultiSelect constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canMultiSelect(model: Diagram): number { return model.tool & DiagramTools.MultipleSelect; } /** * Used to check canZoomPan constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canZoomPan(model: Diagram): number { return model.tool & DiagramTools.ZoomPan; } /** * Used to check canContinuousDraw constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canContinuousDraw(model: Diagram): number { return model.tool & DiagramTools.ContinuousDraw; } /** * Used to check canDrawOnce constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canDrawOnce(model: Diagram): number { return model.tool & DiagramTools.DrawOnce; } /** * Used to check defaultTool constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function defaultTool(model: Diagram): number { return (model.tool & DiagramTools.SingleSelect) || (model.tool & DiagramTools.MultipleSelect); } /** * Used to check canZoom constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canZoom(model: Diagram): number { return model.constraints & DiagramConstraints.Zoom; } /** * Used to check canPan constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canPan(model: Diagram): number { return model.constraints & DiagramConstraints.Pan; } /** * Used to check canUserInteract constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canUserInteract(model: Diagram): number { return model.constraints & DiagramConstraints.UserInteraction; } /** * Used to check canApiInteract constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canApiInteract(model: Diagram): number { return model.constraints & DiagramConstraints.ApiUpdate; } /** * Used to check canPanX constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canPanX(model: Diagram): number { return ((model.constraints & DiagramConstraints.PanX)); } /** * Used to check canPanY constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canPanY(model: Diagram): number { return ((model.constraints & DiagramConstraints.PanY)); } /** * Used to check canZoomTextEdit constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} diagram - provide the Diagram value. * @private */ export function canZoomTextEdit(diagram: Diagram): number { return ((diagram.constraints & DiagramConstraints.ZoomTextEdit)); } /** * Used to check canPageEditable constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} model - provide the Diagram value. * @private */ export function canPageEditable(model: Diagram): number { return canApiInteract(model) || (model.diagramActions & DiagramAction.ToolAction); } /** * Used to check enableReadOnly constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {Diagram} annotation - provide the annotation value. * @param {Diagram} node - provide the node value. * @private */ export function enableReadOnly(annotation: AnnotationModel, node: NodeModel | ConnectorModel): number { let enumValue: number = 0; enumValue = (node instanceof Connector) ? ConnectorConstraints.ReadOnly : NodeConstraints.ReadOnly; if (node.shape.type === 'Text') { return node.constraints & NodeConstraints.ReadOnly; } else if (node.constraints & enumValue) { if (annotation.constraints & AnnotationConstraints.InheritReadOnly) { return 1; } else { return 0; } } else if (annotation.constraints & AnnotationConstraints.ReadOnly) { return 1; } return 0; } /** * Used to check canDraw constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {PointPortModel | NodeModel} port - provide the Diagram value. * @param {Diagram} diagram - provide the Diagram value. * @private */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export function canDraw(port: PointPortModel | NodeModel, diagram: Diagram): number { return port.constraints & PortConstraints.Draw; } /** * Used to check canDrag constraints of the element \ * * @returns { number } Used to check canInConnect constraints of the element .\ * * @param {PointPortModel | NodeModel} port - provide the Diagram value. * @param {Diagram} diagram - provide the Diagram value. * @private */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export function canDrag(port: PointPortModel | NodeModel, diagram: Diagram): number { return port.constraints & PortConstraints.Drag; } /** * Used to check canPreventClearSelection constraints of the element \ * * @returns { boolean } Used to check canInConnect constraints of the element .\ * * @param {PointPortModel | NodeModel} diagramActions - provide the diagramActions value. * @private */ export function canPreventClearSelection(diagramActions: DiagramAction): boolean { if (diagramActions & DiagramAction.PreventClearSelection) { return true; } else { return false; } } /** * Used to check canDrawThumbs \ * * @returns { boolean } Used to check canInConnect constraints of the element .\ * * @param {RendererAction} rendererActions - provide the RendererAction value. * @private */ export function canDrawThumbs(rendererActions: RendererAction): boolean { if (!(rendererActions & RendererAction.DrawSelectorBorder)) { return true; } else { return false; } } /** * Used to check avoidDrawSelector \ * * @returns { boolean } Used to check canInConnect constraints of the element .\ * * @param {RendererAction} rendererActions - provide the RendererAction value. * @private */ export function avoidDrawSelector(rendererActions: RendererAction): boolean { if ((rendererActions & RendererAction.PreventRenderSelector)) { return true; } else { return false; } }
the_stack
import { should } from "chai"; import produce from "immer"; import * as React from "react"; import * as sinon from "sinon"; import { Size } from "@itwin/core-react"; import { fireEvent, render } from "@testing-library/react"; import { act, renderHook } from "@testing-library/react-hooks"; import { addPanelWidget, addTab, createHorizontalPanelState, createNineZoneState, createPanelsState, DraggedPanelSideContext, DragManager, NineZoneDispatch, NineZoneState, PanelSide, PanelStateContext, useAnimatePanelWidgets, WidgetPanelProvider, } from "../../appui-layout-react"; import { createDragItemInfo, setRefValue, TestNineZoneProvider } from "../Providers"; describe("WidgetPanelProvider", () => { it("should render vertical", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (stateDraft) => { stateDraft.panels.left.size = 200; }); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render horizontal", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "top", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (stateDraft) => { stateDraft.panels.top.size = 200; }); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="top" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render collapsed", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (stateDraft) => { stateDraft.panels.left.collapsed = true; }); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render captured", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); const { container } = render( <TestNineZoneProvider state={nineZone} > <DraggedPanelSideContext.Provider value="left"> <WidgetPanelProvider side="left" /> </DraggedPanelSideContext.Provider> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render spanned", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "top", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (stateDraft) => { stateDraft.panels.top.span = true; }); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="top" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render with top spanned", () => { let nineZone = createNineZoneState({ panels: createPanelsState({ top: createHorizontalPanelState("top", { span: true, }), }), }); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should render with span bottom", () => { let nineZone = createNineZoneState({ panels: createPanelsState({ bottom: createHorizontalPanelState("bottom", { span: true, }), }), }); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should dispatch PANEL_INITIALIZE", () => { const dispatch = sinon.stub<NineZoneDispatch>(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); sinon.stub(Element.prototype, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 300 })); render( <TestNineZoneProvider state={nineZone} dispatch={dispatch} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); dispatch.calledOnceWithExactly(sinon.match({ type: "PANEL_INITIALIZE", side: "left", size: 300, })).should.true; }); it("should render multiple widgets", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addPanelWidget(nineZone, "left", "w2", ["t2"]); nineZone = addTab(nineZone, "t1"); nineZone = addTab(nineZone, "t2"); const { container } = render( <TestNineZoneProvider state={nineZone} > <WidgetPanelProvider side="left" /> </TestNineZoneProvider>, ); container.firstChild!.should.matchSnapshot(); }); it("should transition when collapsed", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; Array.from(panel.classList.values()).should.not.contain("nz-transition"); nineZone = produce(nineZone, (draft) => { draft.panels.left.collapsed = true; }); sinon.stub(panel, "getBoundingClientRect") .onFirstCall().returns(DOMRect.fromRect({ width: 200 })) .onSecondCall().returns(DOMRect.fromRect({ width: 300 })); rerender(<WidgetPanelProvider side="left" />); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("300px"); fireEvent.transitionEnd(panel); Array.from(panel.classList.values()).should.not.contain("nz-transition"); }); it("should transition to panel size when opened", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; draft.panels.left.collapsed = true; }); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.collapsed = false; }); sinon.stub(panel, "getBoundingClientRect") .onFirstCall().returns(DOMRect.fromRect({ width: 200 })) .onSecondCall().returns(DOMRect.fromRect({ width: 300 })); rerender(<WidgetPanelProvider side="left" />); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("300px"); }); it("should transition when size changes", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; }); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 300; }); sinon.stub(panel, "getBoundingClientRect") .onFirstCall().returns(DOMRect.fromRect({ width: 200 })) .onSecondCall().returns(DOMRect.fromRect({ width: 300 })); rerender(<WidgetPanelProvider side="left" />); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("300px"); }); it("should restart transition when initializing", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; }); const stub = sinon.stub(HTMLElement.prototype, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 100 })); const dispatch: NineZoneDispatch = (action) => { if (action.type === "PANEL_INITIALIZE") { nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 150; }); stub.reset(); stub .onFirstCall().returns(DOMRect.fromRect({ width: 200 })) .returns(DOMRect.fromRect({ width: 400 })); rerender(<WidgetPanelProvider side="left" />); } }; const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} dispatch={dispatch} {...props} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.size = undefined; }); rerender(<WidgetPanelProvider side="left" />); panel.style.width.should.eq("100px"); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("400px"); }); it("should not transition when resizing", () => { const dragManager = React.createRef<DragManager>(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; }); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider // eslint-disable-line react/display-name state={nineZone} dragManagerRef={dragManager} {...props} />, }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 300; }); dragManager.current!.handleDragStart({ info: createDragItemInfo(), item: { type: "panelGrip", id: "left", }, }); rerender(<WidgetPanelProvider side="left" />); Array.from(panel.classList.values()).should.not.contain("nz-transition"); panel.style.width.should.eq("300px"); }); it("should not resize when collapsing", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; }); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider // eslint-disable-line react/display-name state={nineZone} {...props} />, }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.collapsed = true; }); const stub = sinon.stub(panel, "getBoundingClientRect"); stub .onFirstCall().returns(DOMRect.fromRect({ width: 200 })) .onSecondCall().returns(DOMRect.fromRect({ width: 0 })); rerender(<WidgetPanelProvider side="left" />); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("0px"); stub.reset(); stub.returns(DOMRect.fromRect({ width: 400 })); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 400; }); rerender(<WidgetPanelProvider side="left" />); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.width.should.eq("0px"); }); it("should not transition when from === to", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; }); const { container, rerender } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider // eslint-disable-line react/display-name state={nineZone} {...props} />, }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 300; }); sinon.stub(panel, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 200 })); rerender(<WidgetPanelProvider side="left" />); Array.from(panel.classList.values()).should.not.contain("nz-transition"); panel.style.width.should.eq("300px"); }); it("should persist content size when collapsing", () => { const fakeTimers = sinon.useFakeTimers(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "top", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); const { container, rerender } = render( <WidgetPanelProvider side="top" />, { wrapper: (props) => <TestNineZoneProvider // eslint-disable-line react/display-name state={nineZone} {...props} />, }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; const content = panel.getElementsByClassName("nz-content")[0] as HTMLElement; nineZone = produce(nineZone, (draft) => { draft.panels.top.collapsed = true; }); sinon.stub(panel, "getBoundingClientRect") .onFirstCall().returns(DOMRect.fromRect({ height: 200 })) .onSecondCall().returns(DOMRect.fromRect({ height: 0 })); rerender(<WidgetPanelProvider side="top" />); // Invoke raf callbacks. fakeTimers.tick(1); Array.from(panel.classList.values()).should.contain("nz-transition"); panel.style.height.should.eq("0px"); content.style.minHeight.should.eq("200px"); }); it("should measure panel bounds when resizing", () => { let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; draft.panels.left.collapsed = true; }); const { container } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0]; const spy = sinon.spy(panel, "getBoundingClientRect"); const grip = container.getElementsByClassName("nz-widgetPanels-grip")[0]; const handle = grip.getElementsByClassName("nz-handle")[0]; fireEvent.mouseDown(handle); fireEvent.mouseMove(handle); sinon.assert.called(spy); }); }); describe("useAnimatePanelWidgets", () => { interface WrapperProps { children?: React.ReactNode; state?: NineZoneState; side?: PanelSide; onAfterRender?(): void; } function Wrapper({ children, onAfterRender, state = createNineZoneState(), side = "left", }: WrapperProps) { React.useLayoutEffect(() => { onAfterRender && onAfterRender(); }); return ( <TestNineZoneProvider state={state} > <PanelStateContext.Provider value={state.panels[side]}> {children} </PanelStateContext.Provider> </TestNineZoneProvider> ); } const wrapper = Wrapper; it("should transition when widget is added", () => { const fakeTimers = sinon.useFakeTimers(); let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addTab(state, "t1"); state = addTab(state, "t2"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 600)) .onSecondCall().callsFake(() => { // New widget ref is only set in layout effect setRefValue(result.current.getRef("w2"), w2); return new Size(0, 400); }); sinon.stub(w2, "measure").returns(new Size(0, 200)); setRefValue(result.current.getRef("w1"), w1); state = addPanelWidget(state, "left", "w2", ["t2"]); rerender({ state }); "init".should.eq(result.current.transition); Number(600).should.eq(result.current.sizes.w1); Number(0).should.eq(result.current.sizes.w2); // Invoke raf callbacks. fakeTimers.tick(1); "transition".should.eq(result.current.transition); Number(400).should.eq(result.current.sizes.w1); Number(200).should.eq(result.current.sizes.w2); result.current.handleTransitionEnd(); should().not.exist(result.current.transition); should().not.exist(result.current.sizes.w1); should().not.exist(result.current.sizes.w2); }); it("should transition when widget is removed", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"]); state = addPanelWidget(state, "left", "w3", ["t3"]); state = addTab(state, "t1"); state = addTab(state, "t2"); state = addTab(state, "t3"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; const w3 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 700)); sinon.stub(w3, "measure").returns(new Size(0, 300)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); setRefValue(result.current.getRef("w3"), w3); state = produce(state, (draft) => { draft.panels.left.widgets = ["w1", "w2"]; }); rerender({ state }); "init".should.eq(result.current.transition); Number(300).should.eq(result.current.sizes.w1); Number(600).should.eq(result.current.sizes.w2); }); it("should transition when first widget is removed", () => { const side: PanelSide = "top"; let state = createNineZoneState(); state = addPanelWidget(state, side, "w1", ["t1"]); state = addPanelWidget(state, side, "w2", ["t2"]); state = addPanelWidget(state, side, "w3", ["t3"]); state = addTab(state, "t1"); state = addTab(state, "t2"); state = addTab(state, "t3"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, side, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; const w3 = { measure: () => new Size(), }; sinon.stub(w1, "measure").returns(new Size(300, 0)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(300, 0)) .onSecondCall().returns(new Size(700, 0)); sinon.stub(w3, "measure") .onFirstCall().returns(new Size(300, 0)) .onSecondCall().returns(new Size(200, 0)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); setRefValue(result.current.getRef("w3"), w3); state = produce(state, (draft) => { draft.panels[side].widgets = ["w2", "w3"]; }); rerender({ state, side, }); "init".should.eq(result.current.transition); Number(600).should.eq(result.current.sizes.w2); Number(300).should.eq(result.current.sizes.w3); }); it("should fill upper not minimized widget when widget is removed", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"], { minimized: true }); state = addPanelWidget(state, "left", "w3", ["t3"]); state = addTab(state, "t1"); state = addTab(state, "t2"); state = addTab(state, "t3"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; const w3 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 700)); sinon.stub(w3, "measure").returns(new Size(0, 300)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); setRefValue(result.current.getRef("w3"), w3); state = produce(state, (draft) => { draft.panels.left.widgets = ["w1", "w2"]; }); rerender({ state }); "init".should.eq(result.current.transition); Number(600).should.eq(result.current.sizes.w1); Number(300).should.eq(result.current.sizes.w2); }); it("should fill lower not minimized widget when widget is removed", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"], { minimized: true }); state = addPanelWidget(state, "left", "w3", ["t3"]); state = addTab(state, "t1"); state = addTab(state, "t2"); state = addTab(state, "t3"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; const w3 = { measure: () => new Size(), }; sinon.stub(w1, "measure").returns(new Size(0, 300)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 700)); sinon.stub(w3, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); setRefValue(result.current.getRef("w3"), w3); state = produce(state, (draft) => { draft.panels.left.widgets = ["w2", "w3"]; }); rerender({ state }); "init".should.eq(result.current.transition); Number(300).should.eq(result.current.sizes.w2); Number(600).should.eq(result.current.sizes.w3); }); it("should not fail when last widget is removed", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addTab(state, "t1"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; setRefValue(result.current.getRef("w1"), w1); state = produce(state, (draft) => { draft.panels.left.widgets = []; }); (() => rerender({ state })).should.not.throw(); }); it("should not transition when from and to sizes are equal", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"]); state = addPanelWidget(state, "left", "w3", ["t3"]); state = addTab(state, "t1"); state = addTab(state, "t2"); state = addTab(state, "t3"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; const w3 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 300)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 600)); sinon.stub(w3, "measure").returns(new Size(0, 300)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); setRefValue(result.current.getRef("w3"), w3); state = produce(state, (draft) => { draft.panels.left.widgets = ["w1", "w2"]; }); rerender({ state, }); should().not.exist(result.current.transition); should().not.exist(result.current.sizes.w1); should().not.exist(result.current.sizes.w2); }); it("should init transition when handleBeforeTransition and handlePrepareTransition are invoked", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"]); state = addTab(state, "t1"); state = addTab(state, "t2"); const { result } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 600)) .onSecondCall().returns(new Size(0, 700)); setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => { result.current.handleBeforeTransition(); result.current.handlePrepareTransition(); }); "init".should.eq(result.current.transition); Number(300).should.eq(result.current.sizes.w1); Number(600).should.eq(result.current.sizes.w2); }); it("should not init transition with handlePrepareTransition when ref is unset", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"]); state = addTab(state, "t1"); state = addTab(state, "t2"); const { result } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 600)) .onSecondCall().returns(new Size(0, 700)); setRefValue(result.current.getRef("w1"), w1); // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => { result.current.handleBeforeTransition(); result.current.handlePrepareTransition(); }); should().not.exist(result.current.transition); }); it("should not init transition when ref is unset", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addTab(state, "t1"); state = addTab(state, "t2"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; sinon.stub(w1, "measure") .onFirstCall().returns(new Size(0, 300)) .onSecondCall().returns(new Size(0, 200)); sinon.stub(w2, "measure") .onFirstCall().returns(new Size(0, 600)) .onSecondCall().returns(new Size(0, 700)); setRefValue(result.current.getRef("w1"), w1); state = addPanelWidget(state, "left", "w2", ["t2"]); rerender({ state }); should().not.exist(result.current.transition); }); it("should not re-measure on same render pass if panel.widgets have changed", () => { let state = createNineZoneState(); state = addPanelWidget(state, "left", "w1", ["t1"]); state = addPanelWidget(state, "left", "w2", ["t2"]); state = addTab(state, "t1"); state = addTab(state, "t2"); const { result, rerender } = renderHook(() => useAnimatePanelWidgets(), { initialProps: { onAfterRender: () => { }, state, }, wrapper, }); const w1 = { measure: () => new Size(), }; const w2 = { measure: () => new Size(), }; setRefValue(result.current.getRef("w1"), w1); setRefValue(result.current.getRef("w2"), w2); state = produce(state, (draft) => { draft.panels.left.widgets = ["w1"]; }); const onAfterRender = () => { spy.resetHistory(); result.current.handleBeforeTransition(); }; const spy = sinon.spy(w1, "measure"); rerender({ state, onAfterRender }); sinon.assert.notCalled(spy); }); it("should transition to panel collapse when collapseUnpinned is set", () => { const dispatch = sinon.stub<NineZoneDispatch>(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; draft.panels.left.collapsed = false; draft.panels.left.pinned = false; }); const { container } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} dispatch={dispatch} autoCollapseUnpinnedPanels={true} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; sinon.stub(panel, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 200 })); panel.style.width.should.eq("200px"); fireEvent(panel, new MouseEvent("mouseleave")); dispatch.calledWith({collapsed: true, side: "left", type: "PANEL_SET_COLLAPSED"}).should.be.true; }); it("should not transition to panel collapse when already collapsed and collapseUnpinned is set", () => { const dispatch = sinon.stub<NineZoneDispatch>(); let nineZone = createNineZoneState(); nineZone = addPanelWidget(nineZone, "left", "w1", ["t1"]); nineZone = addTab(nineZone, "t1"); nineZone = produce(nineZone, (draft) => { draft.panels.left.size = 200; draft.panels.left.collapsed = true; draft.panels.left.pinned = false; }); const { container } = render( <WidgetPanelProvider side="left" />, { wrapper: (props) => <TestNineZoneProvider state={nineZone} {...props} dispatch={dispatch} autoCollapseUnpinnedPanels={true} />, // eslint-disable-line react/display-name }, ); const panel = container.getElementsByClassName("nz-widgetPanels-panel")[0] as HTMLElement; sinon.stub(panel, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 0 })); panel.style.width.should.eq("0px"); fireEvent(panel, new MouseEvent("mouseleave")); dispatch.called.should.be.false; }); });
the_stack
import { Browser, commitEntity, getEntityFromElement, getEntitySelector, isCharacterValue, toArray, arrayPush, createElement, addRangeToSelection, createRange, moveChildNodes, getObjectKeys, } from 'roosterjs-editor-dom'; import { ChangeSource, ContentChangedEvent, ContentPosition, Entity, EntityClasses, EntityOperation, EntityOperationEvent, EntityPluginState, HtmlSanitizerOptions, IEditor, Keys, PluginEvent, PluginEventType, PluginMouseUpEvent, PluginWithState, QueryScope, } from 'roosterjs-editor-types'; import type { CompatibleEntityOperation } from 'roosterjs-editor-types/lib/compatibleTypes'; const ENTITY_ID_REGEX = /_(\d{1,8})$/; const ENTITY_CSS_REGEX = '^' + EntityClasses.ENTITY_INFO_NAME + '$'; const ENTITY_ID_CSS_REGEX = '^' + EntityClasses.ENTITY_ID_PREFIX; const ENTITY_TYPE_CSS_REGEX = '^' + EntityClasses.ENTITY_TYPE_PREFIX; const ENTITY_READONLY_CSS_REGEX = '^' + EntityClasses.ENTITY_READONLY_PREFIX; const ALLOWED_CSS_CLASSES = [ ENTITY_CSS_REGEX, ENTITY_ID_CSS_REGEX, ENTITY_TYPE_CSS_REGEX, ENTITY_READONLY_CSS_REGEX, ]; const REMOVE_ENTITY_OPERATIONS: (EntityOperation | CompatibleEntityOperation)[] = [ EntityOperation.Overwrite, EntityOperation.PartialOverwrite, EntityOperation.RemoveFromStart, EntityOperation.RemoveFromEnd, ]; /** * @internal * Entity Plugin helps handle all operations related to an entity and generate entity specified events */ export default class EntityPlugin implements PluginWithState<EntityPluginState> { private editor: IEditor; private state: EntityPluginState; private cancelAsyncRun: () => void; /** * Construct a new instance of EntityPlugin */ constructor() { this.state = { knownEntityElements: [], shadowEntityCache: {}, }; } /** * Get a friendly name of this plugin */ getName() { return 'Entity'; } /** * Initialize this plugin. This should only be called from Editor * @param editor Editor instance */ initialize(editor: IEditor) { this.editor = editor; } /** * Check if the plugin should handle the given event exclusively. * Handle an event exclusively means other plugin will not receive this event in * onPluginEvent method. * If two plugins will return true in willHandleEventExclusively() for the same event, * the final result depends on the order of the plugins are added into editor * @param event The event to check */ willHandleEventExclusively(event: PluginEvent) { return ( event.eventType == PluginEventType.KeyPress && !!(event.rawEvent.target as HTMLElement)?.shadowRoot ); } /** * Dispose this plugin */ dispose() { this.editor = null; this.state.knownEntityElements = []; } /** * Get plugin state object */ getState() { return this.state; } /** * Handle events triggered from editor * @param event PluginEvent object */ onPluginEvent(event: PluginEvent) { switch (event.eventType) { case PluginEventType.MouseUp: this.handleMouseUpEvent(event); break; case PluginEventType.KeyDown: this.handleKeyDownEvent(event.rawEvent); break; case PluginEventType.BeforeCutCopy: if (event.isCut) { this.handleCutEvent(event.rawEvent); } break; case PluginEventType.BeforePaste: this.handleBeforePasteEvent(event.sanitizingOption); break; case PluginEventType.ContentChanged: this.handleContentChangedEvent(event); break; case PluginEventType.EditorReady: this.handleContentChangedEvent(); break; case PluginEventType.ExtractContentWithDom: this.handleExtractContentWithDomEvent(event.clonedRoot); break; case PluginEventType.ContextMenu: this.handleContextMenuEvent(event.rawEvent); break; case PluginEventType.BeforeSetContent: this.handleBeforeSetContentEvent(); break; case PluginEventType.EntityOperation: this.handleEntityOperationEvent(event); break; } } private handleContextMenuEvent(event: UIEvent) { const node = event.target as Node; const entityElement = node && this.editor.getElementAtCursor(getEntitySelector(), node); if (entityElement) { event.preventDefault(); this.triggerEvent(entityElement, EntityOperation.ContextMenu, event); } } private handleCutEvent = (event: ClipboardEvent) => { const range = this.editor.getSelectionRange(); if (range && !range.collapsed) { this.checkRemoveEntityForRange(event); } }; private handleMouseUpEvent(event: PluginMouseUpEvent) { const { rawEvent, isClicking } = event; const node = rawEvent.target as Node; let entityElement: HTMLElement; if ( isClicking && node && !!(entityElement = this.editor.getElementAtCursor(getEntitySelector(), node)) ) { this.triggerEvent(entityElement, EntityOperation.Click, rawEvent); workaroundSelectionIssueForIE(this.editor); } } private handleKeyDownEvent(event: KeyboardEvent) { if ( isCharacterValue(event) || event.which == Keys.BACKSPACE || event.which == Keys.DELETE || event.which == Keys.ENTER ) { const range = this.editor.getSelectionRange(); if (range && !range.collapsed) { this.checkRemoveEntityForRange(event); } } } private handleBeforePasteEvent(sanitizingOption: HtmlSanitizerOptions) { const range = this.editor.getSelectionRange(); if (!range.collapsed) { this.checkRemoveEntityForRange(null /*rawEvent*/); } arrayPush(sanitizingOption.additionalAllowedCssClasses, ALLOWED_CSS_CLASSES); } private handleBeforeSetContentEvent() { this.cacheShadowEntities(this.state.shadowEntityCache); } private handleContentChangedEvent(event?: ContentChangedEvent) { // 1. find removed entities for (let i = this.state.knownEntityElements.length - 1; i >= 0; i--) { const element = this.state.knownEntityElements[i]; if (!this.editor.contains(element)) { this.setIsEntityKnown(element, false /*isKnown*/); if (element.shadowRoot) { this.triggerEvent(element, EntityOperation.RemoveShadowRoot); } } } // 2. collect all new entities const knownIds = this.state.knownEntityElements .map(e => getEntityFromElement(e)?.id) .filter(x => !!x); const newEntities = event?.source == ChangeSource.InsertEntity && event.data ? [event.data as Entity] : this.getExistingEntities().filter(({ wrapper }) => !this.isEntityKnown(wrapper)); // 3. Add new entities to known entity list, and hydrate newEntities.forEach(entity => { const { wrapper, type, id, isReadonly } = entity; entity.id = this.ensureUniqueId(type, id, knownIds); commitEntity(wrapper, type, isReadonly, entity.id); // Use entity.id here because it is newly updated this.handleNewEntity(entity); }); getObjectKeys(this.state.shadowEntityCache).forEach(id => { this.triggerEvent(this.state.shadowEntityCache[id], EntityOperation.Overwrite); delete this.state.shadowEntityCache[id]; }); } private handleEntityOperationEvent(event: EntityOperationEvent) { if (REMOVE_ENTITY_OPERATIONS.indexOf(event.operation) >= 0) { this.cancelAsyncRun?.(); this.cancelAsyncRun = this.editor.runAsync(() => { this.cancelAsyncRun = null; this.handleContentChangedEvent(); }); } } private handleExtractContentWithDomEvent(root: HTMLElement) { toArray(root.querySelectorAll(getEntitySelector())).forEach(element => { element.removeAttribute('contentEditable'); this.triggerEvent(element as HTMLElement, EntityOperation.ReplaceTemporaryContent); }); } private checkRemoveEntityForRange(event: Event) { const editableEntityElements: HTMLElement[] = []; const selector = getEntitySelector(); this.editor.queryElements(selector, QueryScope.OnSelection, element => { if (element.isContentEditable) { editableEntityElements.push(element); } else { this.triggerEvent(element, EntityOperation.Overwrite, event); } }); // For editable entities, we need to check if it is fully or partially covered by current selection, // and trigger different events; if (editableEntityElements.length > 0) { const inSelectionEntityElements = this.editor.queryElements( selector, QueryScope.InSelection ); editableEntityElements.forEach(element => { const isFullyCovered = inSelectionEntityElements.indexOf(element) >= 0; this.triggerEvent( element, isFullyCovered ? EntityOperation.Overwrite : EntityOperation.PartialOverwrite, event ); }); } } private triggerEvent( element: HTMLElement, operation: EntityOperation, rawEvent?: Event, contentForShadowEntity?: DocumentFragment ) { const entity = element && getEntityFromElement(element); if (entity) { this.editor.triggerPluginEvent(PluginEventType.EntityOperation, { operation, rawEvent, entity, contentForShadowEntity, }); } } private handleNewEntity(entity: Entity) { const { wrapper } = entity; const fragment = this.editor.getDocument().createDocumentFragment(); const cache = this.state.shadowEntityCache[entity.id]; delete this.state.shadowEntityCache[entity.id]; if (cache?.shadowRoot) { moveChildNodes(fragment, cache.shadowRoot); } this.triggerEvent(wrapper, EntityOperation.NewEntity, undefined /*rawEvent*/, fragment); // If there is element to hydrate for shadow entity, create shadow root and mount these elements to shadow root // Then trigger AddShadowRoot so that plugins can do further actions if (fragment.firstChild) { if (wrapper.shadowRoot) { moveChildNodes(wrapper.shadowRoot, fragment); } else { this.createShadowRoot(wrapper, fragment); } } else if (wrapper.shadowRoot) { // If no elements to hydrate, remove existing shadow root by cloning a new node this.triggerEvent(wrapper, EntityOperation.RemoveShadowRoot); const newWrapper = wrapper.cloneNode() as HTMLElement; moveChildNodes(newWrapper, wrapper); this.editor.replaceNode(wrapper, newWrapper); entity.wrapper = newWrapper; } this.setIsEntityKnown(entity.wrapper, true /*isKnown*/); } private getExistingEntities(shadowEntityOnly?: boolean): Entity[] { return this.editor .queryElements(getEntitySelector()) .map(getEntityFromElement) .filter(x => !!x && (!shadowEntityOnly || !!x.wrapper.shadowRoot)); } private createShadowRoot(wrapper: HTMLElement, shadowContentContainer?: Node) { if (wrapper.attachShadow) { const shadowRoot = wrapper.attachShadow({ mode: 'open', delegatesFocus: true, }); wrapper.contentEditable = 'false'; this.triggerEvent(wrapper, EntityOperation.AddShadowRoot); moveChildNodes(shadowRoot, shadowContentContainer); return shadowRoot; } } private cacheShadowEntities(cache: Record<string, HTMLElement>) { this.getExistingEntities(true /*shadowEntityOnly*/).forEach(({ wrapper, id }) => { cache[id] = wrapper; }); } private ensureUniqueId(type: string, id: string, knownIds: string[]) { const match = ENTITY_ID_REGEX.exec(id); const baseId = (match ? id.substr(0, id.length - match[0].length) : id) || type; // Make sure entity id is unique let newId = ''; for (let num = (match && parseInt(match[1])) || 0; ; num++) { newId = num > 0 ? `${baseId}_${num}` : baseId; if (knownIds.indexOf(newId) < 0) { knownIds.push(newId); break; } } return newId; } private setIsEntityKnown(wrapper: HTMLElement, isKnown: boolean) { const index = this.state.knownEntityElements.indexOf(wrapper); if (isKnown && index < 0) { this.state.knownEntityElements.push(wrapper); } else if (!isKnown && index >= 0) { this.state.knownEntityElements.splice(index, 1); } } private isEntityKnown(wrapper: HTMLElement) { return this.state.knownEntityElements.indexOf(wrapper) >= 0; } } /** * IE will show a resize border around the readonly content within content editable DIV * This is a workaround to remove it by temporarily move focus out of editor */ const workaroundSelectionIssueForIE = Browser.isIE ? (editor: IEditor) => { editor.runAsync(editor => { const workaroundButton = editor.getCustomData('ENTITY_IE_FOCUS_BUTTON', () => { const button = createElement( { tag: 'button', style: 'overflow:hidden;position:fixed;width:0;height:0;top:-1000px', }, editor.getDocument() ) as HTMLElement; button.onblur = () => { button.style.display = 'none'; }; editor.insertNode(button, { position: ContentPosition.Outside, }); return button; }); workaroundButton.style.display = ''; addRangeToSelection(createRange(workaroundButton, 0)); }); } : () => {};
the_stack
import { BigNumber } from "bignumber.js"; import React, { createContext, useRef, useMemo, useContext, useEffect, useReducer, useState, useCallback, ReactElement, } from "react"; import type { Account, AccountLike, PortfolioRange, Currency, CryptoCurrency, TokenCurrency, AccountPortfolio, Portfolio, CurrencyPortfolio, AssetsDistribution, Unit, } from "../types"; import { getBalanceHistoryWithCountervalue, getPortfolio, getCurrencyPortfolio, getAssetsDistribution, } from "../portfolio"; import { getAccountCurrency, flattenAccounts, getAccountUnit, } from "../account/helpers"; import { initialState, calculate, calculateMany, loadCountervalues, exportCountervalues, importCountervalues, inferTrackingPairForAccounts, } from "./logic"; import type { CounterValuesState, CounterValuesStateRaw, CountervaluesSettings, TrackingPair, } from "./types"; import { useDebounce } from "../hooks/useDebounce"; // Polling is the control object you get from the high level <PollingConsumer>{ polling => ... export type Polling = { // completely wipe all countervalues wipe: () => void; // one shot poll function // TODO: is there any usecases returning promise here? // It's a bit tricky to return Promise with current impl poll: () => void; // start background polling start: () => void; // stop background polling stop: () => void; // true when the polling is in progress pending: boolean; // if the last polling failed, there will be an error error: Error | null | undefined; }; export type Props = { children: React.ReactNode; userSettings: CountervaluesSettings; // the time to wait before the first poll when app starts (allow things to render to not do all at boot time) pollInitDelay?: number; // the minimum time to wait before two automatic polls (then one that happen whatever network/appstate events) autopollInterval?: number; // debounce time before actually fetching debounceDelay?: number; savedState?: CounterValuesStateRaw; }; const CountervaluesPollingContext = createContext<Polling>({ wipe: () => {}, poll: () => {}, start: () => {}, stop: () => {}, pending: false, error: null, }); const CountervaluesContext = createContext<CounterValuesState>(initialState); function trackingPairsHash(a: TrackingPair[]) { return a .map( (p) => `${p.from.ticker}:${p.to.ticker}:${ p.startDate?.toISOString().slice(0, 10) || "" }` ) .sort() .join("|"); } export function useTrackingPairForAccounts( accounts: Account[], countervalue: Currency ): TrackingPair[] { const memo = useMemo( () => inferTrackingPairForAccounts(accounts, countervalue), [accounts, countervalue] ); const ref = useRef(memo); if (trackingPairsHash(ref.current) === trackingPairsHash(memo)) { return ref.current; } ref.current = memo; return memo; } export function Countervalues({ children, userSettings, pollInitDelay = 1 * 1000, autopollInterval = 120 * 1000, debounceDelay = 1000, savedState, }: Props): ReactElement { const debouncedUserSettings = useDebounce(userSettings, debounceDelay); const [{ state, pending, error }, dispatch] = useReducer( fetchReducer, initialFetchState ); // flag used to trigger a loadCountervalues const [triggerLoad, setTriggerLoad] = useState(false); // trigger poll only when userSettings changes. in a debounced way. useEffect(() => { setTriggerLoad(true); }, [debouncedUserSettings]); // loadCountervalues logic useEffect(() => { if (pending || !triggerLoad) return; setTriggerLoad(false); dispatch({ type: "pending", }); loadCountervalues(state, userSettings).then( (state) => { dispatch({ type: "success", payload: state, }); }, (error) => { dispatch({ type: "error", payload: error, }); } ); }, [pending, state, userSettings, triggerLoad]); // save the state when it changes useEffect(() => { if (!savedState?.status || !Object.keys(savedState.status).length) return; dispatch({ type: "setCounterValueState", payload: importCountervalues(savedState, userSettings), }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [savedState]); // manage the auto polling loop and the interface for user land to trigger a reload const [isPolling, setIsPolling] = useState(true); useEffect(() => { if (!isPolling) return; let pollingTimeout; function pollingLoop() { setTriggerLoad(true); pollingTimeout = setTimeout(pollingLoop, autopollInterval); } pollingTimeout = setTimeout(pollingLoop, pollInitDelay); return () => clearTimeout(pollingTimeout); }, [autopollInterval, pollInitDelay, isPolling]); const polling = useMemo<Polling>( () => ({ wipe: () => { dispatch({ type: "wipe", }); }, poll: () => setTriggerLoad(true), start: () => setIsPolling(true), stop: () => setIsPolling(false), pending, error, }), [pending, error] ); return ( <CountervaluesPollingContext.Provider value={polling}> <CountervaluesContext.Provider value={state}> {children} </CountervaluesContext.Provider> </CountervaluesPollingContext.Provider> ); } type Action = | { type: "success"; payload: CounterValuesState; } | { type: "error"; payload: Error; } | { type: "pending"; } | { type: "wipe"; } | { type: "setCounterValueState"; payload: CounterValuesState; }; type FetchState = { state: CounterValuesState; pending: boolean; error?: Error; }; const initialFetchState: FetchState = { state: initialState, pending: false, }; function fetchReducer(state: FetchState, action: Action): FetchState { switch (action.type) { case "success": return { state: action.payload, pending: false, error: undefined, }; case "error": return { ...state, pending: false, error: action.payload }; case "pending": return { ...state, pending: true, error: undefined }; case "wipe": return { state: initialState, pending: false, error: undefined, }; case "setCounterValueState": return { ...state, state: action.payload }; default: return state; } } export function useCountervaluesPolling(): Polling { return useContext(CountervaluesPollingContext); } export function useCountervaluesState(): CounterValuesState { return useContext(CountervaluesContext); } export function useCountervaluesExport(): CounterValuesStateRaw { const state = useContext(CountervaluesContext); return useMemo(() => exportCountervalues(state), [state]); } export function useCalculate(query: { value: number; from: Currency; to: Currency; disableRounding?: boolean; date?: Date | null | undefined; reverse?: boolean; }): number | null | undefined { const state = useCountervaluesState(); return calculate(state, query); } export function useCalculateMany( dataPoints: Array<{ value: number; date: Date | null | undefined; }>, query: { from: Currency; to: Currency; disableRounding?: boolean; reverse?: boolean; } ): Array<number | null | undefined> { const state = useCountervaluesState(); // TODO how to approach perf for this? hash function of the datapoints? responsability on user land? return calculateMany(state, dataPoints, query); } // TODO perf of the useCalculate*, does it even worth worrying? // TODO move to portfolio module (I couldn't make useCountervaluesState to work there) export function useBalanceHistoryWithCountervalue({ account, range, to, }: { account: AccountLike; range: PortfolioRange; to: Currency; }): AccountPortfolio { const from = getAccountCurrency(account); const state = useCountervaluesState(); return useMemo( () => getBalanceHistoryWithCountervalue(account, range, (_, value, date) => { const countervalue = calculate(state, { value: value.toNumber(), from, to, disableRounding: true, date, }); return typeof countervalue === "number" ? new BigNumber(countervalue) : countervalue; }), [account, from, to, range, state] ); } export function usePortfolio({ accounts, range, to, }: { accounts: Account[]; range: PortfolioRange; to: Currency; }): Portfolio { const state = useCountervaluesState(); return useMemo( () => getPortfolio(accounts, range, (from, value, date) => { const countervalue = calculate(state, { value: value.toNumber(), from, to, disableRounding: true, date, }); return typeof countervalue === "number" ? new BigNumber(countervalue) : countervalue; }), [accounts, range, state, to] ); } export function useCurrencyPortfolio({ accounts: rawAccounts, range, to, currency, }: { accounts: Account[]; range: PortfolioRange; to: Currency; currency: CryptoCurrency | TokenCurrency; }): CurrencyPortfolio { const accounts = flattenAccounts(rawAccounts).filter( (a) => getAccountCurrency(a) === currency ); const state = useCountervaluesState(); return useMemo( () => getCurrencyPortfolio(accounts, range, (from, value, date) => { const countervalue = calculate(state, { value: value.toNumber(), from, to, disableRounding: true, date, }); return typeof countervalue === "number" ? new BigNumber(countervalue) : countervalue; }), [accounts, range, state, to] ); } export function useDistribution({ accounts, to, }: { accounts: Account[]; to: Currency; }): AssetsDistribution { const calc = useCalculateCountervalueCallback({ to, }); return useMemo(() => { return getAssetsDistribution(accounts, calc, { minShowFirst: 6, maxShowFirst: 6, showFirstThreshold: 0.95, }); }, [accounts, calc]); } export function useCalculateCountervalueCallback({ to, }: { to: Currency; }): (from: Currency, value: BigNumber) => BigNumber | null | undefined { const state = useCountervaluesState(); return useCallback( (from: Currency, value: BigNumber): BigNumber | null | undefined => { const countervalue = calculate(state, { value: value.toNumber(), from, to, disableRounding: true, }); return typeof countervalue === "number" ? new BigNumber(countervalue) : countervalue; }, [to, state] ); } export function useSendAmount({ account, fiatCurrency, cryptoAmount, }: { account: AccountLike; fiatCurrency: Currency; cryptoAmount: BigNumber; }): { cryptoUnit: Unit; fiatAmount: BigNumber; fiatUnit: Unit; calculateCryptoAmount: (fiatAmount: BigNumber) => BigNumber; } { const cryptoCurrency = getAccountCurrency(account); const fiatCountervalue = useCalculate({ from: cryptoCurrency, to: fiatCurrency, value: cryptoAmount.toNumber(), disableRounding: true, }); const fiatAmount = new BigNumber(fiatCountervalue ?? 0); const fiatUnit = fiatCurrency.units[0]; const cryptoUnit = getAccountUnit(account); const state = useCountervaluesState(); const calculateCryptoAmount = useCallback( (fiatAmount: BigNumber) => { const cryptoAmount = new BigNumber( calculate(state, { from: cryptoCurrency, to: fiatCurrency, value: fiatAmount.toNumber(), reverse: true, }) ?? 0 ); return cryptoAmount; }, [state, cryptoCurrency, fiatCurrency] ); return { cryptoUnit, fiatAmount, fiatUnit, calculateCryptoAmount, }; }
the_stack
import { Component } from '@angular/core'; import { NzModalRef } from 'ng-zorro-antd'; import { BehaviorSubject, combineLatest, EMPTY, Observable, of, Subject, Subscription } from 'rxjs'; import { NgSerializerService } from '@kaiu/ng-serializer'; import { CustomItem } from '../../../modules/custom-items/model/custom-item'; import { CustomItemsFacade } from '../../../modules/custom-items/+state/custom-items.facade'; import { catchError, delay, expand, filter, first, map, mergeMap, skip, skipUntil, switchMap, tap } from 'rxjs/operators'; import * as Papa from 'papaparse'; import { I18nToolsService } from '../../../core/tools/i18n-tools.service'; import { LazyDataService } from '../../../core/data/lazy-data.service'; import { CustomItemFolder } from '../../../modules/custom-items/model/custom-item-folder'; import { DataService } from '../../../core/api/data.service'; import { Ingredient } from '../../../model/garland-tools/ingredient'; @Component({ selector: 'app-custom-items-import-popup', templateUrl: './custom-items-import-popup.component.html', styleUrls: ['./custom-items-import-popup.component.less'] }) export class CustomItemsImportPopupComponent { public format = 'TC'; public folder: CustomItemFolder; public hideUpload = false; public error: string; public errorDetails: string; public folders$: Observable<CustomItemFolder[]> = this.customItemsFacade.allCustomItemFolders$; public availableCraftJobs: any[] = []; public state: 'PARSING' | 'SAVING' = 'PARSING'; public totalSaving = 1; public savingDone = 0; private craftTypes: string[] = [ 'Woodworking', 'Smithing', 'Armorcraft', 'Goldsmithing', 'Leatherworking', 'Clothcraft', 'Cooking', 'Alchemy' ]; public handleFile = (event: any) => { delete this.error; delete this.errorDetails; const reader = new FileReader(); let data = ''; reader.onload = ((_) => { return (e) => { data += e.target.result; }; })(event.file); reader.onloadend = () => { this.processFile(data); }; // Read in the image file as a data URL. reader.readAsText(event.file); this.hideUpload = true; return new Subscription(); }; constructor(private modalRef: NzModalRef, private serializer: NgSerializerService, private customItemsFacade: CustomItemsFacade, private i18n: I18nToolsService, private lazyData: LazyDataService, private db: DataService) { } public getAccept(): string { switch (this.format) { case 'TC': return '.tcitem'; case 'CSV-EM': return '.csv'; default: return ''; } } private processFile(content: string): void { try { let operation$: Observable<any>; switch (this.format) { case 'TC': operation$ = this.processTCImport(content); break; case 'CSV-EM': operation$ = this.processCSVEMImport(content); break; } operation$.pipe(first()).subscribe(() => { this.modalRef.close(); }); } catch (err) { this.error = 'CUSTOM_ITEMS.IMPORT.Corrupted_file'; this.errorDetails = err.message; this.hideUpload = false; } } private processTCImport(content: string): Observable<any> { const json = decodeURIComponent(escape(atob(content))); const data: any[] = JSON.parse(json); const items: CustomItem[] = this.serializer .deserialize<CustomItem>(data, [CustomItem]) .map(item => { item.afterDeserialized(); return item; }); const sortedItems = this.topologicalSort(items); let index = -1; this.totalSaving = sortedItems.length; return this.customItemsFacade.allCustomItems$.pipe( first(), expand((allItems) => { if (sortedItems[index] === undefined) { return EMPTY; } const itemData = sortedItems[index]; const item = new CustomItem(); Object.assign(item, itemData); delete item.authorId; delete item.folderId; item.$key = this.customItemsFacade.createId(); // If it has requirements, map them to the new items. if (item.requires !== undefined) { item.requires = item.requires.map(req => { if (!req.custom) { return req; } const previousReq = items.find(i => i.$key === req.id); const newReq = allItems.find(i => { return i.name === previousReq.name && i.$key !== undefined && i.createdAt.toMillis() === previousReq.createdAt.toMillis(); }); req.id = newReq ? newReq.$key : 'missing item'; return req; }); } this.customItemsFacade.addCustomItem(item); if (this.folder !== undefined) { this.folder.items.push(item.$key); this.customItemsFacade.updateCustomItemFolder(this.folder); } return this.customItemsFacade.allCustomItems$.pipe( filter(availableItems => { return availableItems.some(i => i.name === item.name && i.$key !== undefined && i.createdAt.toMillis() === item.createdAt.toMillis()); }), first() ); }), tap(() => { this.savingDone++; index++; }), skip(sortedItems.length - 1) ); } private topologicalSort(data: CustomItem[]): CustomItem[] { const res: CustomItem[] = []; const doneList: boolean[] = []; while (data.length > res.length) { let resolved = false; for (const item of data) { if (res.indexOf(item) > -1) { // item already in resultset continue; } resolved = true; if (item.requires !== undefined) { for (const dep of item.requires) { // We have to check if it's not a precraft, as some dependencies aren't resolvable inside the current array. const depIsInArray = data.find(row => row.id === dep.id) !== undefined; if (!doneList[dep.id] && depIsInArray) { // there is a dependency that is not met: resolved = false; break; } } } if (resolved) { // All dependencies are met: doneList[item.id] = true; res.push(item); } } } return res; } private processCSVEMImport(content: string): Observable<any> { const allItems = this.lazyData.allItems; const parsed = Papa.parse(content); // First of all, let's parse all rows and create items from them, as we know they'll need to be created. const parsedToItems = parsed.data .filter(row => row.length > 1) .map(row => { const item = new CustomItem(); item.$key = this.customItemsFacade.createId(); item.name = row[4]; item.yield = +row[5]; item.realItemId = +row[45]; item.craftedBy = [{ recipeId: row[1], jobId: +this.craftTypes.indexOf(row[2]) + 8, icon: '', itemId: +row[45], level: 80, stars_tooltip: '' }]; item.craftedBy[0].icon = `https://garlandtools.org/db/images/${this.availableCraftJobs.find(j => j.id === item.craftedBy[0].jobId).abbreviation}.png`; return { item: item, meta: row }; }); // Then, for each parsed row, let's populate an ingredient array, for the same purpose (will contain only the ones that aren't listed as recipe already) const ingredients: CustomItem[] = []; parsedToItems.forEach(entry => { for (let ingredientIndex = 6; ingredientIndex < 25; ingredientIndex += 2) { if (entry.meta[ingredientIndex] === '') { continue; } const ingredient = new CustomItem(); ingredient.name = entry.meta[ingredientIndex]; const matches = Object.keys(allItems).filter(key => { return this.i18n.getName(allItems[key]).toLowerCase() === ingredient.name.toLowerCase(); }); if (!ingredients.some(i => i.name === ingredient.name)) { ingredients.push(ingredient); } if (matches) { ingredient.realItemId = +matches; } } }); // Once ingredients are ready, let's see what needs to be custom or what is already an item return combineLatest( ingredients.map(ingredient => { const meta = parsed.data.find(row => row[4] === ingredient.name); // If it has no real item id found, it's a custom one. if (ingredient.realItemId === undefined || ingredient.realItemId === 0) { return of({ item: ingredient, meta: meta, isCustom: true }); } // Else try to get it on GT return this.db.getItem(ingredient.realItemId).pipe( map(() => { return { item: ingredient, meta: meta, isCustom: false }; }), // Error = 404 = custom item catchError(() => { return of({ item: ingredient, meta: meta, isCustom: true }); }) ); }) ).pipe( map(ingredientEntries => { const allCustomItems = []; parsedToItems.concat(ingredientEntries.filter((entry) => entry.isCustom)).forEach(entry => { if (entry.isCustom) { entry.item.$key = this.customItemsFacade.createId(); } if (!allCustomItems.some(i => i.item.name === entry.item.name)) { allCustomItems.push(entry); } }); return this.topologicalSort(allCustomItems.map(({ item, meta }) => { for (let ingredientIndex = 6; ingredientIndex < 25; ingredientIndex += 2) { if (meta === undefined || meta[ingredientIndex] === '') { continue; } const ingredientName = meta[ingredientIndex]; item.requires = item.requires || []; const ingredientEntry = allCustomItems.find(i => i.item.name === ingredientName); const realIngredientId = Object.keys(allItems).filter(key => { return this.i18n.getName(allItems[key]).toLowerCase() === ingredientName.toLowerCase(); }); const ingredientId = ingredientEntry ? ingredientEntry.item.$key || ingredientEntry.item.realItemId : realIngredientId; const req: Ingredient = { id: ingredientId, amount: meta[ingredientIndex + 1] }; if (ingredientEntry) { req.custom = true; } item.requires.push(req); } return item; })); }), tap(sortedItems => { this.totalSaving = sortedItems.length; sortedItems.forEach(item => { if (this.folder !== undefined && this.folder !== null) { this.folder.items.push(item.$key); } }); }), switchMap((sortedItems) => { this.state = 'SAVING'; const doing$ = new BehaviorSubject(0); const complete$ = new Subject(); return doing$.pipe( delay(250), mergeMap(index => { const item = sortedItems[index]; this.customItemsFacade.addCustomItem(item); return this.customItemsFacade.allCustomItems$.pipe( first(), tap(() => { this.savingDone++; if (sortedItems[index + 1] !== undefined) { doing$.next(index + 1); } else { complete$.next(); } }) ); }), skipUntil(complete$) ); }), tap(() => { if (this.folder !== undefined) { this.customItemsFacade.updateCustomItemFolder(this.folder); } }) ); } }
the_stack
type URIPath = { scheme: string, authority: string | undefined, port: number | undefined, path: string, extension: string | undefined; }; type URIPathGlob = { scheme: string, authority: string | undefined, port: number | undefined, path: string, selection: "*" | "**" | undefined, filter: string | undefined } type Version = { major: number, minor: number, fix: number, patch: number, branch: string | undefined }; type VersionConstraint = { major: number, minor: number, //min minor fix: number, branch: string | undefined }; type PackageFormat = "inline" | "component" | "service"; type Contact = { name: string, role: string, email: string | undefined, url: URIPath | undefined }; type SourceInfo = { bsqsource: URIPathGlob[], entrypoints: URIPathGlob[], testfiles: URIPathGlob[] }; type ConfigRun = { main: string, args: any[] | undefined }; type ConfigBuild = { out: URIPath | undefined }; type ConfigTest = { flavors: ("sym" | "icpp" | "err" | "chk")[], dirs: URIPathGlob[] | "*" }; type ConfigAppTest = { flavors: ("sym" | "icpp" | "err" | "chk")[], dirs: URIPathGlob[] | "*" }; type ConfigFuzz = { dirs: URIPathGlob[] | "*" }; type Config<T> = { name: string, macros: string[], globalmacros: string[], buildlevel: "debug" | "test" | "release" params: T }; type Dependency = { name: string, version: VersionConstraint, format: PackageFormat, //string encoded internal: boolean, src: URIPath | undefined //optional fixed lookup -- repo, manager ref, file system -- otherwise we do standard resolution }; //exports must include scope component of the form `${name}${version.major}` type Package = { name: string; version: Version, //string encoded description: string, keywords: string[], homepage: URIPath | undefined, //string encoded repository: URIPath | undefined, //string encoded license: string, people: Contact[], src: SourceInfo, documentation: { files: URIPath[], //string encoded root: URIPath //string encoded } | undefined, configs: { run: Config<ConfigRun>[], build: Config<ConfigBuild>[], test: Config<ConfigTest>[], apptest: Config<ConfigAppTest>[], fuzz: Config<ConfigFuzz>[] }, dependencies: Dependency[], devDependencies: Dependency[] }; function parseURIScheme(str: string): [string | undefined, string] { if (process.platform === "win32") { if (/^[a-zA-Z]:\\/.test(str) || str.startsWith(".\\") || str.startsWith("..\\")) { return ["file", str]; } if (str.startsWith("./") || str.startsWith("../")) { return ["file", str]; } } if ((process.platform === "linux" || process.platform === "darwin")) { if (str.startsWith("/") || str.startsWith("~/") || str.startsWith("./") || str.startsWith("../")) { return ["file", str]; } } const schemematch = /:/.exec(str); if (schemematch !== null) { return [schemematch[0].slice(0, schemematch.index), str.slice(schemematch.index + 1)]; } else { return [undefined, str]; } } function parseURIAuthority(str: string): [string | undefined, number | undefined, string] { if (!str.startsWith("//")) { return [undefined, undefined, str]; } const authoritymatch = /^\/\/[a-zA-Z0-9.]+/.exec(str); if (authoritymatch !== null) { const tail = str.slice(authoritymatch[0].length + 1); const port = /^:[0-9]{1, 5}/.exec(tail); if (port === null) { return [authoritymatch[0].slice(2, authoritymatch[0].length), undefined, tail]; } else { const tail2 = tail.slice(port[0].length + 1); const portval = Number.parseInt(port[0].slice(1)); return [authoritymatch[0].slice(2, authoritymatch[0].length), portval, tail2] } } else { return [undefined, undefined, str]; } } function parseURIPathBase(str: string): { scheme: string, authority: string | undefined, port: number | undefined, path: string, extension: string | undefined } | undefined { const [scheme, rstr1] = parseURIScheme(str); if (scheme === undefined) { return undefined; } const [authority, port, rstr2] = parseURIAuthority(rstr1); const extidx = rstr2.lastIndexOf("."); if (extidx === -1) { return undefined; } const extension = rstr2.slice(extidx + 1); return { scheme: scheme, authority: authority, port: port, path: rstr2, extension: extension }; } function parseURIPath(pp: any): URIPath | undefined { if (typeof (pp) !== "string") { return undefined; } return parseURIPathBase(pp); } function parseURIPathGlob(pg: any): URIPathGlob | undefined { if (typeof (pg) !== "string") { return undefined; } const mm = /([*]{1,2}([.][a-zA-Z0-9]+)?)$/.exec(pg); const ubase = parseURIPathBase(mm !== null ? pg.slice(0, pg.length - mm[0].length) : pg); if (ubase === undefined) { return undefined; } if (mm === null) { return { scheme: ubase.scheme, authority: ubase.authority, port: ubase.port, path: ubase.path, selection: undefined, filter: undefined }; } else { return { scheme: ubase.scheme, authority: ubase.authority, port: ubase.port, path: ubase.path, selection: mm[0].startsWith("**") ? "**" : "*", filter: mm[0].includes(".") ? mm[0].slice(mm[0].indexOf(".") + 1) : undefined }; } } function parseVersion(vv: any): Version | undefined { if (typeof (vv) !== "string") { return undefined; } if (!/^[0-9]{1,5}\.[0-9]{1,5}\.[0-9]{1,5}\.[0-9]{1,5}(-[a-zA-Z-0-9_]+)?$/.test(vv)) { return undefined; } let branch: string | undefined = undefined; if (vv.includes("-")) { const bidx = vv.indexOf("-"); branch = vv.slice(bidx + 1); vv = vv.slice(0, bidx); } const pvals = (vv as string).split("."); return { major: Number.parseInt(pvals[0]), minor: Number.parseInt(pvals[1]), fix: Number.parseInt(pvals[2]), patch: Number.parseInt(pvals[3]), branch: branch }; } function parseVersionConstraint(vv: any): VersionConstraint | undefined { if (typeof (vv) !== "string") { return undefined; } if (!/^[0-9]{1-5}\.[0-9]{1-5}\.[0-9]{1-5}\.[*](-[a-zA-Z-0-9_]+)?$/.test(vv)) { return undefined; } let branch: string | undefined = undefined; if (vv.includes("-")) { const bidx = vv.indexOf("-"); branch = vv.slice(bidx + 1); vv = vv.slice(0, bidx); } const pvals = (vv as string).split("."); return { major: Number.parseInt(pvals[0]), minor: Number.parseInt(pvals[1]), fix: Number.parseInt(pvals[2]), branch: branch }; } function parsePackageFormat(pf: any): PackageFormat | undefined { if (pf !== "inline" && pf !== "component" && pf !== "service") { return undefined; } return pf; } function parseContact(ct: any): Contact | undefined { if (ct === null || typeof (ct) !== "object") { return undefined; } if (typeof (ct["name"]) !== "string" || typeof (ct["role"]) !== "string") { return undefined; } if (ct["email"] !== undefined && typeof (ct["email"]) !== "string") { return undefined; } if (ct["url"] !== undefined && typeof (ct["url"]) !== "string") { return undefined; } return { name: ct["name"], role: ct["role"], email: ct["email"], url: ct["url"] } } function parseSourceInfo(si: any): SourceInfo | undefined { if (si === null || typeof (si) !== "object") { return undefined; } if (!Array.isArray(si["bsqsource"])) { return undefined; } const bsqsrc = si["bsqsource"].map((src) => { const pp = parseURIPathGlob(src); if (pp === undefined) { return undefined; } if (pp.selection !== undefined && pp.filter === undefined) { pp.filter = ".bsq"; } return pp.filter === ".bsq" ? pp : undefined; }); if (!Array.isArray(si["entrypoints"])) { return undefined; } const entrypoints = si["entrypoints"].map((src) => { const pp = parseURIPathGlob(src); if (pp === undefined) { return undefined; } if (pp.selection !== undefined && pp.filter === undefined) { pp.filter = ".bsqapi"; } return (pp.filter === undefined || pp.filter === ".bsqapi") ? pp : undefined; }); if (!Array.isArray(si["testfiles"])) { return undefined; } const testfiles = si["testfiles"].map((src) => { const pp = parseURIPathGlob(src); if (pp === undefined) { return undefined; } if (pp.selection !== undefined && pp.filter === undefined) { pp.filter = ".bsqtest"; } return (pp.filter === undefined || pp.filter === ".bsqtest") ? pp : undefined; }); if (bsqsrc.includes(undefined) || entrypoints.includes(undefined) || testfiles.includes(undefined)) { return undefined; } return { bsqsource: bsqsrc as URIPathGlob[], entrypoints: entrypoints as URIPathGlob[], testfiles: testfiles as URIPathGlob[] }; } function parseConfigRun(cfg: any): ConfigRun | undefined { if (typeof (cfg["main"]) !== "string") { return undefined; } if (cfg["args"] === undefined) { return { main: cfg["main"], args: undefined } } else { if (!Array.isArray(cfg["args"])) { return undefined; } return { main: cfg["main"], args: cfg["args"] } } } function parseConfigBuild(cfg: any): ConfigBuild | undefined { const out = parseURIPath(cfg["out"]); if (out === undefined) { return undefined; } return { out: out }; } function parseConfigTest(cfg: any): ConfigTest | undefined { let flavors: ("sym" | "icpp" | "err" | "chk")[] = ["sym", "icpp", "chk"]; if (cfg["flavors"] !== undefined) { if (!Array.isArray(cfg["flavors"]) || cfg["flavors"].some((ff) => (ff !== "sym" && ff !== "icpp" && ff !== "err" && ff !== "chk"))) { return undefined; } flavors = cfg["flavors"] as ("sym" | "icpp" | "err" | "chk")[]; } let dirs: URIPathGlob[] | "*" = "*"; if (cfg["dirs"] !== undefined) { if (!Array.isArray(cfg["dirs"])) { return undefined; } const dirsmap = cfg["dirs"].map((dd) => parseURIPathGlob(dd)); if (dirsmap.includes(undefined)) { return undefined; } dirs = dirsmap as URIPathGlob[]; } return { flavors: flavors, dirs: dirs }; } function parseConfigAppTest(cfg: any): ConfigAppTest | undefined { let flavors: ("sym" | "icpp" | "err" | "chk")[] = ["sym", "icpp", "err"]; if (cfg["flavors"] !== undefined) { if (!Array.isArray(cfg["flavors"]) || cfg["flavors"].some((ff) => (ff !== "sym" && ff !== "icpp" && ff !== "err" && ff !== "chk"))) { return undefined; } flavors = cfg["flavors"] as ("sym" | "icpp" | "err" | "chk")[]; } let dirs: URIPathGlob[] | "*" = "*"; if (cfg["dirs"] !== undefined) { if (!Array.isArray(cfg["dirs"])) { return undefined; } const dirsmap = cfg["dirs"].map((dd) => parseURIPathGlob(dd)); if (dirsmap.includes(undefined)) { return undefined; } dirs = dirsmap as URIPathGlob[]; } return { flavors: flavors, dirs: dirs }; } function parseConfigFuzz(cfg: any): ConfigFuzz | undefined { let dirs: URIPathGlob[] | "*" = "*"; if (cfg["dirs"] !== undefined) { if (!Array.isArray(cfg["dirs"])) { return undefined; } const dirsmap = cfg["dirs"].map((dd) => parseURIPathGlob(dd)); if (dirsmap.includes(undefined)) { return undefined; } dirs = dirsmap as URIPathGlob[]; } return { dirs: dirs }; } function parseConfig<T>(cf: any, tag: "run" | "build" | "test" | "apptest" | "fuzz"): Config<T> | undefined { if (cf === null || typeof (cf) !== "object") { return undefined; } if (typeof (cf["name"]) !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(cf["name"])) { return undefined; } let macros: string[] = []; if (cf["macros"] !== undefined) { if (!Array.isArray(cf["macros"])) { return undefined; } const macrosmap = cf["macros"].map((mm) => { if (typeof (mm) !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(mm)) { return undefined; } return mm; }); if(macrosmap.includes(undefined)) { return undefined; } macros = macrosmap as string[]; } let globalmacros: string[] = []; if (cf["globalmacros"] !== undefined) { if (!Array.isArray(cf["globalmacros"])) { return undefined; } const globalmacrosmap = cf["globalmacros"].map((mm) => { if (typeof (mm) !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(mm)) { return undefined; } return mm; }); if (globalmacrosmap.includes(undefined)) { return undefined; } globalmacros = globalmacrosmap as string[]; } let buildlevel: "debug" | "test" | "release" = "debug"; let pc: any = undefined; if (tag === "run") { buildlevel = "test"; pc = parseConfigRun(cf); } else if (tag === "build") { buildlevel = "test"; pc = parseConfigBuild(cf); } else if (tag === "test") { buildlevel = "test"; pc = parseConfigTest(cf); } else if (tag === "apptest") { buildlevel = "test"; pc = parseConfigAppTest(cf); } else { buildlevel = "test"; pc = parseConfigFuzz(cf); } if(cf["buildlevel"] !== undefined) { if (cf["buildlevel"] !== "debug" && cf["buildlevel"] !== "test" && cf["buildlevel"] !== "release") { return undefined } buildlevel = cf["buildlevel"] as "debug" | "test" | "release"; } return { name: cf["name"] as string, macros: macros as string[], globalmacros: globalmacros as string[], buildlevel: buildlevel, params: pc as T }; } function parseAppDependency(dep: any): Dependency | undefined { if (dep === null || typeof (dep) !== "object") { return undefined; } const format = parsePackageFormat(dep["format"]); if (format === undefined) { return undefined; } if (typeof (dep["name"]) !== "string") { return undefined } const vc = parseVersionConstraint(dep["version"]); if (vc === undefined) { return undefined; } let src: URIPath | undefined = undefined; if (dep["src"] !== undefined) { src = parseURIPath(dep["src"]); if (src === undefined) { return undefined; } } return { name: dep["name"] as string, version: vc, format: format, internal: dep["internal"] === true, src: src }; } function parseDevDependency(dep: any): Dependency | undefined { if (dep === null || typeof (dep) !== "object") { return undefined; } const format = parsePackageFormat(dep["format"]); if (format === undefined) { return undefined; } if (typeof (dep["name"]) !== "string") { return undefined } const vc = parseVersionConstraint(dep["version"]); if (vc === undefined) { return undefined; } let src: URIPath | undefined = undefined; if (dep["src"] !== undefined) { src = parseURIPath(dep["src"]); if (src === undefined) { return undefined; } } return { name: dep["name"] as string, version: vc, format: format, internal: true, src: src }; } function parsePackage(jp: any): Package | string { if (jp === null || typeof (jp) !== "object") { return "package not a valid JSON object"; } if (typeof (jp["name"]) !== "string") { return "invalid 'name' field"; } const version = parseVersion(jp["version"]); if (version === undefined) { return "invalid 'version' field"; } if (typeof (jp["description"]) !== "string") { return "invalid 'description' field"; } let keywords: string[] = []; if (jp["keywords"] !== undefined) { if (!Array.isArray(jp["keywords"]) || jp["keywords"].some((ee) => typeof (ee) !== "string")) { return "invalid 'keywords'"; } keywords = jp["keywords"]; } let homepage: URIPath | undefined = undefined; if (jp["homepage"] !== undefined) { homepage = parseURIPath(jp["homepage"]); if (homepage === undefined) { return "invalid 'homepage' field"; } } let repository: URIPath | undefined = undefined; if (jp["repository"] !== undefined) { repository = parseURIPath(jp["repository"]); if (repository === undefined) { return "invalid 'repository' field"; } } if (typeof (jp["license"]) !== "string") { return "invalid 'license' field"; } let people: Contact[] = []; if (jp["people"] !== undefined) { if (!Array.isArray(jp["people"])) { return "'people' field should be an array"; } const peoplemap = jp["people"].map((pp) => parseContact(pp)); if (peoplemap.includes(undefined)) { return "invalid 'contact' in 'people' field"; } people = peoplemap as Contact[]; } const srcinfo = parseSourceInfo(jp["src"]); if (srcinfo === undefined) { return "invalid 'src' field"; } let documentation: { files: URIPath[], root: URIPath } | undefined = undefined; if (jp["documentation"] !== undefined) { if (jp["documentation"] === null || typeof (jp["documentation"]) !== "object") { return "invalid 'documentation' field"; } let docfiles: URIPath[] = []; if (!Array.isArray(jp["documentation"]["files"])) { return "'documentation.files' needs to be an array"; } const docfilesmap = jp["documentation"]["files"].map((df) => parseURIPath(df)); if (docfilesmap.includes(undefined)) { return "invalid 'documentation.files' entry"; } docfiles = docfilesmap as URIPath[]; const docroot = parseURIPath(jp["documentation"]["root"]); if (docroot === undefined) { return "invalid 'documentation.root' field"; } documentation = { files: docfiles, root: docroot }; } let runconfigs: Config<ConfigRun>[] = []; let buildconfigs: Config<ConfigBuild>[] = []; let testconfigs: Config<ConfigTest>[] = []; let apptestconfigs: Config<ConfigAppTest>[] = []; let fuzzconfigs: Config<ConfigFuzz>[] = []; const configs = jp["configs"]; if (configs !== undefined) { if (configs === null || typeof (configs) !== "object") { return "invalid 'config' field"; } if (configs["run"] !== undefined) { if (!Array.isArray(configs["run"])) { return "expected array for 'config.run' field"; } const rcfg = configs["run"].map((cfg) => parseConfig<ConfigRun>(cfg, "run")); if (rcfg.includes(undefined)) { return "invalid entry in 'config.run' array"; } runconfigs = rcfg as Config<ConfigRun>[]; } if (configs["build"] !== undefined) { if (!Array.isArray(configs["build"])) { return "expected array for 'config.build' field"; } const rcfg = configs["build"].map((cfg) => parseConfig<ConfigBuild>(cfg, "build")); if (rcfg.includes(undefined)) { return "invalid entry in 'config.build' array"; } buildconfigs = rcfg as Config<ConfigBuild>[]; } if (configs["test"] !== undefined) { if (!Array.isArray(configs["test"])) { return "expected array for 'config.test' field"; } const rcfg = configs["test"].map((cfg) => parseConfig<ConfigTest>(cfg, "test")); if (rcfg.includes(undefined)) { return "invalid entry in 'config.test' array"; } testconfigs = rcfg as Config<ConfigTest>[]; } if (configs["apptest"] !== undefined) { if (!Array.isArray(configs["apptest"])) { return "expected array for 'config.apptest' field"; } const rcfg = configs["apptest"].map((cfg) => parseConfig<ConfigAppTest>(cfg, "apptest")); if (rcfg.includes(undefined)) { return "invalid entry in 'config.apptest' array"; } apptestconfigs = rcfg as Config<ConfigAppTest>[]; } if (configs["fuzz"] !== undefined) { if (!Array.isArray(configs["fuzz"])) { return "expected array for 'config.fuzz' field"; } const rcfg = configs["fuzz"].map((cfg) => parseConfig<ConfigFuzz>(cfg, "fuzz")); if (rcfg.includes(undefined)) { return "invalid entry in 'config.fuzz' array"; } fuzzconfigs = rcfg as Config<ConfigFuzz>[]; } } let dependencies: Dependency[] = []; if (jp["dependencies"] !== undefined) { if (!Array.isArray(jp["dependencies"])) { return "expected array for 'dependencies' field"; } const dependenciesmap = jp["dependencies"].map((dep) => parseAppDependency(dep)); if (dependenciesmap.includes(undefined)) { return "invalid entry in 'dependencies' array"; } dependencies = dependenciesmap as Dependency[]; } let devDependencies: Dependency[] = []; if (jp["devDependencies"] !== undefined) { if (!Array.isArray(jp["devDependencies"])) { return "expected array for 'devDependencies' field"; } const devDependenciesmap = jp["devDependencies"].map((pp) => parseDevDependency(pp)); if (devDependenciesmap.includes(undefined)) { return "invalid entry in 'devDependencies' array"; } devDependencies = devDependenciesmap as Dependency[]; } return { name: jp["name"] as string, version: version, description: jp["description"] as string, keywords: keywords, homepage: homepage, repository: repository, license: jp["license"] as string, people: people, src: srcinfo, documentation: documentation, configs: { run: runconfigs, build: buildconfigs, test: testconfigs, apptest: apptestconfigs, fuzz: fuzzconfigs }, dependencies: dependencies, devDependencies: devDependencies }; } export { URIPath, URIPathGlob, Version, VersionConstraint, PackageFormat, Contact, SourceInfo, ConfigRun, ConfigBuild, ConfigTest, ConfigAppTest, ConfigFuzz, Config, Dependency, Package, parseURIPath, parseURIPathGlob, parsePackage };
the_stack
import Common, { Chain } from '@ethereumjs/common' /** * Default hardfork rules to run tests against */ export const DEFAULT_FORK_CONFIG = 'Istanbul' /** * Tests which should be fixed */ export const SKIP_BROKEN = [ 'ForkStressTest', // Only BlockchainTest, temporary till fixed (2020-05-23) 'ChainAtoChainB', // Only BlockchainTest, temporary, along expectException fixes (2020-05-23) 'undefinedOpcodeFirstByte', // https://github.com/ethereumjs/ethereumjs-monorepo/issues/1271 (2021-05-26) // In these tests, we have access to two forked chains. Their total difficulty is equal. There are errors in the second chain, but we have no reason to execute this chain if the TD remains equal. 'blockChainFrontierWithLargerTDvsHomesteadBlockchain2_FrontierToHomesteadAt5', 'blockChainFrontierWithLargerTDvsHomesteadBlockchain_FrontierToHomesteadAt5', 'HomesteadOverrideFrontier_FrontierToHomesteadAt5', ] /** * Tests skipped due to system specifics / design considerations */ export const SKIP_PERMANENT = [ 'SuicidesMixingCoinbase', // sucides to the coinbase, since we run a blockLevel we create coinbase account. 'static_SuicidesMixingCoinbase', // sucides to the coinbase, since we run a blockLevel we create coinbase account. 'ForkUncle', // Only BlockchainTest, correct behaviour unspecified (?) 'UncleFromSideChain', // Only BlockchainTest, same as ForkUncle, the TD is the same for two diffent branches so its not clear which one should be the finally chain ] /** * tests running slow (run from time to time) */ export const SKIP_SLOW = [ 'Call50000', 'Call50000_ecrec', 'Call50000_identity', 'Call50000_identity2', 'Call50000_sha256', 'Call50000_rip160', 'Call50000bytesContract50_1', 'Call50000bytesContract50_2', 'Call1MB1024Calldepth', 'static_Call1MB1024Calldepth', 'static_Call50000', 'static_Call50000_ecrec', 'static_Call50000_identity', 'static_Call50000_identity2', 'static_Call50000_rip160', 'static_Return50000_2', 'Callcode50000', 'Return50000', 'Return50000_2', 'static_Call50000', 'static_Call50000_ecrec', 'static_Call50000_identity', 'static_Call50000_identity2', 'static_Call50000_sha256', 'static_Call50000_rip160', 'static_Call50000bytesContract50_1', 'static_Call50000bytesContract50_2', 'static_Call1MB1024Calldepth', 'static_Callcode50000', 'static_Return50000', 'static_Return50000_2', 'QuadraticComplexitySolidity_CallDataCopy', 'CALLBlake2f_MaxRounds', 'randomStatetest94_Istanbul', // vmPerformance tests 'ackermann', 'fibonacci', 'loop-add-10M', 'loop-divadd-10M', 'loop-divadd-unr100-10M', 'loop-exp', 'loop-mul', 'manyFunctions100', 'loopMul', 'loopExp', ] /** * VMTests have been deprecated, see https://github.com/ethereum/tests/issues/593 * skipVM test list is currently not used but might be useful in the future since VMTests * have now been converted to BlockchainTests, see https://github.com/ethereum/tests/pull/680 * Disabling this due to ESLint, but will keep it here for possible future reference */ /*const SKIP_VM = [ // slow performance tests 'loop-mul', 'loop-add-10M', 'loop-divadd-10M', 'loop-divadd-unr100-10M', 'loop-exp-16b-100k', 'loop-exp-1b-1M', 'loop-exp-2b-100k', 'loop-exp-32b-100k', 'loop-exp-4b-100k', 'loop-exp-8b-100k', 'loop-exp-nop-1M', 'loop-mulmod-2M', 'ABAcalls0', 'ABAcallsSuicide0', 'ABAcallsSuicide1', 'sha3_bigSize', 'CallRecursiveBomb0', 'CallToNameRegistrator0', 'CallToPrecompiledContract', 'CallToReturn1', 'PostToNameRegistrator0', 'PostToReturn1', 'callcodeToNameRegistrator0', 'callcodeToReturn1', 'callstatelessToNameRegistrator0', 'callstatelessToReturn1', 'createNameRegistrator', 'randomTest643', ]*/ /** * Returns an alias for specified hardforks to meet test dependencies requirements/assumptions. * @param {String} forkConfig - the name of the hardfork for which an alias should be returned * @returns {String} Either an alias of the forkConfig param, or the forkConfig param itself */ export function getRequiredForkConfigAlias(forkConfig: string) { // Chainstart is also called Frontier and is called as such in the tests if (String(forkConfig).match(/^chainstart$/i)) { return 'Frontier' } // TangerineWhistle is named EIP150 (attention: misleading name) // in the client-independent consensus test suite if (String(forkConfig).match(/^tangerineWhistle$/i)) { return 'EIP150' } // SpuriousDragon is named EIP158 (attention: misleading name) // in the client-independent consensus test suite if (String(forkConfig).match(/^spuriousDragon$/i)) { return 'EIP158' } // Run the Istanbul tests for MuirGlacier since there are no dedicated tests if (String(forkConfig).match(/^muirGlacier/i)) { return 'Istanbul' } // Petersburg is named ConstantinopleFix // in the client-independent consensus test suite if (String(forkConfig).match(/^petersburg$/i)) { return 'ConstantinopleFix' } return forkConfig } const normalHardforks = [ 'chainstart', 'homestead', 'dao', 'tangerineWhistle', 'spuriousDragon', 'byzantium', 'constantinople', 'petersburg', 'istanbul', 'muirGlacier', 'berlin', 'london', ] const transitionNetworks: any = { ByzantiumToConstantinopleFixAt5: { byzantium: 0, constantinople: 5, petersburg: 5, dao: null, finalSupportedFork: 'petersburg', startFork: 'byzantium', }, EIP158ToByzantiumAt5: { spuriousDragon: 0, byzantium: 5, dao: null, finalSupportedFork: 'byzantium', startFork: 'spuriousDragon', }, FrontierToHomesteadAt5: { chainstart: 0, homestead: 5, dao: null, finalSupportedFork: 'homestead', startFork: 'chainstart', }, HomesteadToDaoAt5: { homestead: 0, dao: 5, finalSupportedFork: 'dao', startFork: 'homestead', }, HomesteadToEIP150At5: { homestead: 0, tangerineWhistle: 5, dao: null, finalSupportedFork: 'tangerineWhistle', startFork: 'homestead', }, BerlinToLondonAt5: { berlin: 0, london: 5, dao: null, finalSupportedFork: 'london', startFork: 'berlin', }, } const testLegacy: any = { chainstart: true, homestead: true, tangerineWhistle: true, spuriousDragon: true, byzantium: true, constantinople: true, petersburg: true, istanbul: false, muirGlacier: false, berlin: false, ByzantiumToConstantinopleFixAt5: false, EIP158ToByzantiumAt5: false, FrontierToHomesteadAt5: false, HomesteadToDaoAt5: false, HomesteadToEIP150At5: false, BerlinToLondonAt5: false, } /** * Returns an array of dirs to run tests on * @param network (fork identifier) * @param {string} Test type (BlockchainTests/StateTests) */ export function getTestDirs(network: string, testType: string) { const testDirs = [testType] for (const key in testLegacy) { if (key.toLowerCase() == network.toLowerCase() && testLegacy[key]) { // Tests for HFs before Istanbul have been moved under `LegacyTests/Constantinople`: // https://github.com/ethereum/tests/releases/tag/v7.0.0-beta.1 testDirs.push('LegacyTests/Constantinople/' + testType) break } } return testDirs } /** * Returns a Common for the given network (a test parameter) * @param {String} network - the network field of a test * @returns {Common} the Common which should be used */ export function getCommon(network: string) { const networkLowercase = network.toLowerCase() if (normalHardforks.map((str) => str.toLowerCase()).includes(networkLowercase)) { // normal hard fork, return the common with this hard fork // find the right upper/lowercased version const hfName = normalHardforks.reduce((previousValue, currentValue) => currentValue.toLowerCase() == networkLowercase ? currentValue : previousValue ) const mainnetCommon = new Common({ chain: Chain.Mainnet, hardfork: hfName }) const hardforks = mainnetCommon.hardforks() const testHardforks = [] for (const hf of hardforks) { // check if we enable this hf // disable dao hf by default (if enabled at block 0 forces the first 10 blocks to have dao-hard-fork in extraData of block header) if (mainnetCommon.gteHardfork(hf.name) && hf.name != 'dao') { // this hardfork should be activated at block 0 testHardforks.push({ name: hf.name, // Current type definition Partial<Chain> in Common is currently not allowing to pass in forkHash // forkHash: hf.forkHash, block: 0, }) } else { // disable hardforks newer than the test hardfork (but do add "support" for it, it just never gets activated) testHardforks.push({ name: hf.name, //forkHash: hf.forkHash, block: null, }) } } return Common.forCustomChain( 'mainnet', { hardforks: testHardforks, }, hfName ) } else { // this is not a "default fork" network, but it is a "transition" network. we will test the VM if it transitions the right way const transitionForks = transitionNetworks[network] || transitionNetworks[network.substring(0, 1).toUpperCase() + network.substr(1)] if (!transitionForks) { throw new Error('network not supported: ' + network) } const mainnetCommon = new Common({ chain: Chain.Mainnet, hardfork: transitionForks.finalSupportedFork, }) const hardforks = mainnetCommon.hardforks() const testHardforks = [] for (const hf of hardforks) { if (mainnetCommon.gteHardfork(hf.name)) { // this hardfork should be activated at block 0 const forkBlockNumber = transitionForks[hf.name] testHardforks.push({ name: hf.name, // forkHash: hf.forkHash, block: forkBlockNumber === null ? null : forkBlockNumber || 0, // if forkBlockNumber is defined as null, disable it, otherwise use block number or 0 (if its undefined) }) } else { // disable the hardfork testHardforks.push({ name: hf.name, // forkHash: hf.forkHash, block: null, }) } } return Common.forCustomChain( 'mainnet', { hardforks: testHardforks, }, transitionForks.startFork ) } } const expectedTestsFull: any = { BlockchainTests: { Chainstart: 4385, Homestead: 7001, Dao: 0, TangerineWhistle: 4255, SpuriousDragon: 4305, Byzantium: 15379, Constantinople: 32750, Petersburg: 32735, Istanbul: 35378, MuirGlacier: 35378, Berlin: 33, ByzantiumToConstantinopleFixAt5: 3, EIP158ToByzantiumAt5: 3, FrontierToHomesteadAt5: 12, HomesteadToDaoAt5: 18, HomesteadToEIP150At5: 3, BerlinToLondonAt5: 0, }, GeneralStateTests: { Chainstart: 896, Homestead: 1847, Dao: 0, TangerineWhistle: 969, SpuriousDragon: 1094, Byzantium: 4626, Constantinople: 10402, Petersburg: 10397, Istanbul: 10715, MuirGlacier: 10715, Berlin: 13065, ByzantiumToConstantinopleFixAt5: 0, EIP158ToByzantiumAt5: 0, FrontierToHomesteadAt5: 0, HomesteadToDaoAt5: 0, HomesteadToEIP150At5: 0, BerlinToLondonAt5: 0, }, } /** * Returns the amount of expected tests for a given fork, assuming all tests are ran */ export function getExpectedTests(fork: string, name: string) { if (expectedTestsFull[name] == undefined) { return } for (const key in expectedTestsFull[name]) { if (fork.toLowerCase() == key.toLowerCase()) { return expectedTestsFull[name][key] } } } /** * Returns an aggregated array with the tests to skip * @param choices comma-separated list with skip options, e.g. BROKEN,PERMANENT * @param defaultChoice if to use `NONE` or `ALL` as default choice * @returns array with test names */ export function getSkipTests(choices: string, defaultChoice: string): string[] { let skipTests: string[] = [] if (!choices) { choices = defaultChoice } choices = choices.toLowerCase() if (choices !== 'none') { const choicesList = choices.split(',') const all = choicesList.includes('all') if (all || choicesList.includes('broken')) { skipTests = skipTests.concat(SKIP_BROKEN) } if (all || choicesList.includes('permanent')) { skipTests = skipTests.concat(SKIP_PERMANENT) } if (all || choicesList.includes('slow')) { skipTests = skipTests.concat(SKIP_SLOW) } } return skipTests }
the_stack
import { configure, runInAction } from "mobx"; import _loadWithXhr from "../../../../lib/Core/loadWithXhr"; import Terria from "../../../../lib/Models/Terria"; import { getLineStyleCesium } from "../../../../lib/Models/Catalog/Esri/esriLineStyle"; import ArcGisFeatureServerCatalogItem, { convertEsriPointSizeToPixels, convertEsriColorToCesiumColor } from "../../../../lib/Models/Catalog/Esri/ArcGisFeatureServerCatalogItem"; import CommonStrata from "../../../../lib/Models/Definition/CommonStrata"; import isDefined from "../../../../lib/Core/isDefined"; import { JsonArray } from "../../../../lib/Core/Json"; import i18next from "i18next"; import ColorMaterialProperty from "terriajs-cesium/Source/DataSources/ColorMaterialProperty"; import JulianDate from "terriajs-cesium/Source/Core/JulianDate"; import PolylineDashMaterialProperty from "terriajs-cesium/Source/DataSources/PolylineDashMaterialProperty"; import Color from "terriajs-cesium/Source/Core/Color"; import ConstantProperty from "terriajs-cesium/Source/DataSources/ConstantProperty"; import GeoJsonDataSource from "terriajs-cesium/Source/DataSources/GeoJsonDataSource"; configure({ enforceActions: "observed", computedRequiresReaction: true }); interface ExtendedLoadWithXhr { (): any; load: { (...args: any[]): any; calls: any }; } const loadWithXhr: ExtendedLoadWithXhr = <any>_loadWithXhr; describe("ArcGisFeatureServerCatalogItem", function() { const featureServerUrl = "http://example.com/arcgis/rest/services/Water_Network/FeatureServer/2"; const featureServerUrl2 = "http://example.com/arcgis/rest/services/Parks/FeatureServer/3"; const featureServerUrlStyleLines = "http://example.com/arcgis/rest/services/styles/FeatureServer/0"; let terria: Terria; let item: ArcGisFeatureServerCatalogItem; beforeEach(function() { terria = new Terria({ baseUrl: "./" }); item = new ArcGisFeatureServerCatalogItem("test", terria); const realLoadWithXhr = loadWithXhr.load; // We replace calls to real servers with pre-captured JSON files so our testing is isolated, but reflects real data. spyOn(loadWithXhr, "load").and.callFake(function(...args: any[]) { let url = args[0]; if (url.match("Water_Network/FeatureServer")) { url = url.replace(/^.*\/FeatureServer/, "FeatureServer"); url = url.replace( /FeatureServer\/query\?f=json&layerDefs=%7B2%3A%22.*%22%7D$/i, "layerDefs.json" ); url = url.replace(/FeatureServer\/2\/?\?.*/i, "2.json"); args[0] = "test/ArcGisFeatureServer/Water_Network/" + url; } else if (url.match("Parks/FeatureServer")) { url = url.replace(/^.*\/FeatureServer/, "FeatureServer"); url = url.replace( /FeatureServer\/query\?f=json&layerDefs=%7B3%3A%22.*%22%7D$/i, "layerDefs.json" ); url = url.replace(/FeatureServer\/3\/?\?.*/i, "3.json"); args[0] = "test/ArcGisFeatureServer/Parks/" + url; } else if (url.match("styles/FeatureServer")) { url = url.replace(/^.*\/FeatureServer/, "FeatureServer"); url = url.replace( /FeatureServer\/query\?f=json&layerDefs=%7B0%3A%22.*%22%7D$/i, "layerDefs.json" ); url = url.replace(/FeatureServer\/0\/?\?.*/i, "lines.json"); args[0] = "test/ArcGisFeatureServer/styles/" + url; } return realLoadWithXhr(...args); }); }); it("has a type and typeName", function() { expect(item.type).toBe("esri-featureServer"); expect(item.typeName).toBe( i18next.t("models.arcGisFeatureServerCatalogItem.name") ); }); it("supports zooming to extent", function() { expect(item.disableZoomTo).toBeFalsy(); }); it("supports show info", function() { expect(item.disableAboutData).toBeFalsy(); }); describe("after loading metadata", function() { beforeEach(async function() { runInAction(() => { item.setTrait("definition", "url", featureServerUrl); }); await item.loadMetadata(); }); it("defines a rectangle", function() { expect(item.rectangle).toBeDefined(); if (item.rectangle) { expect(item.rectangle.west).toEqual(-179.999987937519); expect(item.rectangle.south).toEqual(-55.90222504885724); expect(item.rectangle.east).toEqual(179.999987937519); expect(item.rectangle.north).toEqual(81.29054454173075); } }); it("defines info", function() { const dataDescription = i18next.t( "models.arcGisMapServerCatalogItem.dataDescription" ); const copyrightText = i18next.t( "models.arcGisMapServerCatalogItem.copyrightText" ); expect(item.info.map(({ name }) => name)).toEqual([ dataDescription, copyrightText ]); expect(item.info.map(({ content }) => content)).toEqual([ "Water Data", "Water Copyright" ]); }); }); describe("loadMapItems", function() { it("properly loads a single layer", async function() { runInAction(() => { item.setTrait(CommonStrata.definition, "url", featureServerUrl); }); await item.loadMapItems(); expect(item.geoJsonItem).toBeDefined(); if (isDefined(item.geoJsonItem)) { const geoJsonData = item.geoJsonItem.geoJsonData; expect(geoJsonData).toBeDefined(); if (isDefined(geoJsonData)) { expect(geoJsonData.type).toEqual("FeatureCollection"); const features = <JsonArray>geoJsonData.features; expect(features.length).toEqual(13); } } }); }); describe("updateEntityWithEsriStyle", function() { it("correctly uses symbol.outline.color to style polyline.", async function() { runInAction(() => { item.setTrait(CommonStrata.definition, "url", featureServerUrl2); }); await item.loadMetadata(); await item.loadMapItems(); const expectedOutlineWidth = convertEsriPointSizeToPixels(1); const expectedPolygonFilledColor: number = Color.fromBytes( 215, 203, 247, 255 ).toRgba(); const expectedPolygonOutlineColor: number = Color.fromBytes( 110, 110, 110, 255 ).toRgba(); const expectedPolylineColor = expectedPolygonOutlineColor; const aTime = new JulianDate(); item.mapItems.map(mapItem => { (mapItem as GeoJsonDataSource).entities.values.map(entity => { expect(entity.polygon).toBeDefined(); if (entity.polygon !== undefined) { // Waiting on better Cesium typings // entity.polygon.material.color returns a Property, but types // suggest it returns a Color. Type casts are neccessary due to this. const actualPolygonOutlineWidth = (<ConstantProperty>( entity.polygon.outlineWidth )).getValue(aTime); expect(actualPolygonOutlineWidth).toEqual(expectedOutlineWidth); const acutualPolygonColor = (<ConstantProperty>( (<unknown>(<ColorMaterialProperty>entity.polygon.material).color) )) .getValue(aTime) .toRgba(); expect(acutualPolygonColor).toEqual(expectedPolygonFilledColor); const actualPolygonOutlineColor = (<ConstantProperty>( (<unknown>( (<ColorMaterialProperty>entity.polygon.outlineColor).color )) )) .getValue(aTime) .toRgba(); expect(actualPolygonOutlineColor).toEqual( expectedPolygonOutlineColor ); } expect(entity.polyline).toBeDefined(); if (entity.polyline !== undefined) { const acutalPolylineColor = (<ConstantProperty>( (<unknown>( (<ColorMaterialProperty>entity?.polyline?.material).color )) )) .getValue(aTime) .toRgba(); expect(acutalPolylineColor).toEqual(expectedPolylineColor); } }); }); }); }); describe("esriSLS", function() { it("properly loads features", async function() { runInAction(() => { item.setTrait( CommonStrata.definition, "url", featureServerUrlStyleLines ); }); await item.loadMapItems(); expect(item.geoJsonItem).toBeDefined(); if (isDefined(item.geoJsonItem)) { const geoJsonData = item.geoJsonItem.geoJsonData; expect(geoJsonData).toBeDefined(); if (isDefined(geoJsonData)) { expect(geoJsonData.type).toEqual("FeatureCollection"); const features = <JsonArray>geoJsonData.features; expect(features.length).toEqual(13); } } }); it("properly styles features", async function() { runInAction(() => { item.setTrait( CommonStrata.definition, "url", featureServerUrlStyleLines ); }); await item.loadMapItems(); expect(item.geoJsonItem).toBeDefined(); expect(item.mapItems).toBeDefined(); expect(item.mapItems.length).toEqual(1); const mapItem = item.mapItems[0]; const entities = (mapItem as GeoJsonDataSource).entities.values; expect(entities).toBeDefined(); expect(entities.length).toEqual(13); // first item const time = new JulianDate(); expect(entities[0].polyline).toBeDefined(); expect( entities[0]?.polyline?.material instanceof ColorMaterialProperty ).toBeTruthy(); expect(entities[0]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[1].polyline).toBeDefined(); expect( entities[1]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[1]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSDot")); expect( (<ConstantProperty>( (<unknown>( (<PolylineDashMaterialProperty>entities[1]?.polyline?.material) .color )) )).getValue(time) ).toEqual(convertEsriColorToCesiumColor([20, 158, 206, 255])); expect(entities[1]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[2].polyline).toBeDefined(); expect( entities[2]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>entities[2]?.polyline?.material) .dashPattern ).toBeUndefined(); expect(entities[2]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[3].polyline).toBeDefined(); expect( entities[3]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[3]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSDashDot")); expect(entities[3]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[4].polyline).toBeDefined(); expect( entities[4]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[4]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSDashDotDot")); expect(entities[4]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[5].polyline).toBeDefined(); expect( entities[5]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[5]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSLongDash")); expect(entities[5]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[6].polyline).toBeDefined(); expect( entities[6]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[6]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSLongDashDot")); expect(entities[6]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[7].polyline).toBeDefined(); expect( entities[7]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[7]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSShortDash")); expect(entities[7]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[8].polyline).toBeDefined(); expect( entities[8]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[8]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSShortDot")); expect(entities[8]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[9].polyline).toBeDefined(); expect( entities[9]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[9]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSShortDashDot")); expect(entities[9]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[10].polyline).toBeDefined(); expect( entities[10]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>( entities[10]?.polyline?.material )).dashPattern?.getValue(time) ).toEqual(getLineStyleCesium("esriSLSShortDashDotDot")); expect(entities[10]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[11].polyline).toBeDefined(); expect( entities[11]?.polyline?.material instanceof ColorMaterialProperty ).toBeTruthy(); expect(entities[11]?.polyline?.show?.getValue(time)).toBeFalsy(); expect(entities[11]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(1.5) ); expect(entities[12].polyline).toBeDefined(); expect( entities[12]?.polyline?.material instanceof PolylineDashMaterialProperty ).toBeTruthy(); expect( (<PolylineDashMaterialProperty>entities[12]?.polyline?.material) .dashPattern ).toBeUndefined(); expect(entities[12]?.polyline?.width?.getValue(time)).toEqual( convertEsriPointSizeToPixels(4.5) ); }); }); });
the_stack
import { RuleTester } from "eslint"; import rule from "../src/rules/compat"; const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2020, sourceType: "module" }, parser: require.resolve("@typescript-eslint/parser"), settings: { lintAllEsApis: true, }, }); ruleTester.run("compat", rule, { valid: [ // Ignore ES APIs if config detected { code: ` Array.from() `, settings: { browsers: ["ExplorerMobile 10"] }, }, // Feature detection Cases { code: ` if (fetch) { fetch() } `, settings: { browsers: ["ExplorerMobile 10"] }, }, { code: ` if (Array.prototype.flat) { new Array.flat() } `, settings: { browsers: ["ExplorerMobile 10"] }, }, { code: ` if (fetch && otherConditions) { fetch() } `, settings: { browsers: ["ExplorerMobile 10"] }, }, { code: ` if (window.fetch) { fetch() } `, settings: { browsers: ["ExplorerMobile 10"] }, }, { code: ` if ('fetch' in window) { fetch() } `, settings: { browsers: ["ExplorerMobile 10"] }, }, { code: "window", settings: { browsers: ["ExplorerMobile 10"] }, }, { code: "document.fonts()", settings: { browsers: ["edge 79"] }, }, // Import cases { code: ` import { Set } from 'immutable'; new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` const { Set } = require('immutable'); new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` const { Set } = require('immutable'); new Set(); `, settings: { browsers: ["current node"] }, }, { code: ` const { Set } = require('immutable'); new Set(); `, settings: { browsers: ["ie 9", "current node"] }, }, { code: ` const Set = require('immutable').Set; new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` Promise.resolve() `, settings: { browsers: ["node 10"] }, }, { code: ` const { Set } = require('immutable'); (() => { new Set(); })(); `, settings: { browsers: ["ie 9"] }, }, { code: ` import Set from 'immutable'; new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` function Set() {} new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` const Set = () => {}; new Set(); `, settings: { browsers: ["ie 9"] }, }, { code: ` const bar = () => { const Set = () => {}; new Set(); } `, settings: { browsers: ["ie 9"] }, }, { code: ` const bar = () => { class Set {} new Set() } `, settings: { browsers: ["ie 9"] }, }, { code: ` const bar = () => { const Set = {} new Set() } `, settings: { browsers: ["ie 9"] }, }, { code: ` const bar = () => { function Set() {} new Set() } `, settings: { browsers: ["ie 9"] }, }, { code: "document.documentElement()", settings: { browsers: ["Safari 11", "Opera 57", "Edge 17"] }, }, { code: "document.getElementsByTagName()", settings: { browsers: ["Safari 11", "Opera 57", "Edge 17"] }, }, { code: 'Promise.resolve("foo")', settings: { polyfills: ["Promise"], browsers: ["ie 8"] }, }, { code: "history.back()", settings: { browsers: ["Safari 11", "Opera 57", "Edge 17"] }, }, "document.querySelector()", { code: "new ServiceWorker()", settings: { browsers: ["chrome 57", "firefox 50"] }, }, { code: "document.currentScript()", settings: { browsers: ["chrome 57", "firefox 50", "safari 10", "edge 14"], }, }, { code: "document.querySelector()", settings: { browsers: ["ChromeAndroid 80"], }, }, { code: "document.hasFocus()", settings: { browsers: ["Chrome 27"], }, }, { code: "new URL()", settings: { browsers: ["ChromeAndroid 78", "ios 11"], }, }, { code: "document.currentScript('some')", settings: { browsers: ["chrome 57", "firefox 50", "safari 10", "edge 14"], }, }, { code: "WebAssembly.compile()", settings: { browsers: ["chrome 40"], polyfills: ["WebAssembly", "WebAssembly.compile"], }, }, { code: "new IntersectionObserver(() => {}, {});", settings: { browsers: ["chrome 58"] }, }, { code: "new URL('http://example')", settings: { browsers: ["chrome 32", "safari 7.1", "firefox 26"], }, }, { code: "new URLSearchParams()", settings: { browsers: ["chrome 49", "safari 10.1", "firefox 44"], }, }, ], invalid: [ { code: "window?.fetch?.('example.com')", settings: { browsers: ["ie 9"] }, errors: [ { message: "fetch is not supported in IE 9", }, ], }, { settings: { browsers: ["ie 9"], }, code: ` navigator.hardwareConcurrency; navigator.serviceWorker; new SharedWorker(); `, errors: [ { message: "navigator.hardwareConcurrency() is not supported in IE 9", }, { message: "navigator.serviceWorker() is not supported in IE 9", }, { message: "SharedWorker is not supported in IE 9", }, ], }, { settings: { browsers: ["ie 8"], }, code: ` // it should throw an error here, but it doesn't const event = new CustomEvent("cat", { detail: { hazcheeseburger: true } }); window.dispatchEvent(event); `, errors: [ { message: "CustomEvent is not supported in IE 8", }, ], }, { code: "Array.from()", settings: { browsers: ["ie 8"], }, errors: [ { message: "Array.from() is not supported in IE 8", }, ], }, { code: "Promise.allSettled()", settings: { browsers: [ "Chrome >= 72", "Firefox >= 72", "Safari >= 12", "Edge >= 79", ], }, errors: [ { message: "Promise.allSettled() is not supported in Safari 12, Chrome 72", }, ], }, { code: "location.origin", settings: { browsers: ["ie 10"] }, errors: [ { message: "location.origin() is not supported in IE 10", }, ], }, { code: ` import { Map } from 'immutable'; new Set() `, settings: { browsers: ["ie 9"] }, errors: [ { message: "Set is not supported in IE 9", type: "NewExpression", }, ], }, { code: "new Set()", settings: { browsers: ["ie 9"] }, errors: [ { message: "Set is not supported in IE 9", type: "NewExpression", }, ], }, { code: "new TypedArray()", settings: { browsers: ["ie 9"] }, errors: [ { message: "TypedArray is not supported in IE 9", type: "NewExpression", }, ], }, { code: "new Int8Array()", settings: { browsers: ["ie 9"] }, errors: [ { message: "Int8Array is not supported in IE 9", type: "NewExpression", }, ], }, { code: "new AnimationEvent", settings: { browsers: ["chrome 40"] }, errors: [ { message: "AnimationEvent is not supported in Chrome 40", type: "NewExpression", }, ], }, { code: "Object.values({})", settings: { browsers: ["safari 9"] }, errors: [ { message: "Object.values() is not supported in Safari 9", type: "MemberExpression", }, ], }, { code: "new ServiceWorker()", settings: { browsers: ["chrome 31"] }, errors: [ { message: "ServiceWorker is not supported in Chrome 31", type: "NewExpression", }, ], }, { code: "new IntersectionObserver(() => {}, {});", settings: { browsers: ["chrome 49"] }, errors: [ { message: "IntersectionObserver is not supported in Chrome 49", type: "NewExpression", }, ], }, { code: "WebAssembly.compile()", settings: { browsers: [ "Samsung 4", "Safari 10.1", "Opera 12.1", "OperaMini all", "iOS 10.3", "ExplorerMobile 10", "IE 10", "Edge 14", "Blackberry 7", "Baidu 7.12", "UCAndroid 11.8", "QQAndroid 1.2", ], }, errors: [ { message: "WebAssembly is not supported in Safari 10.1, Opera 12.1, iOS Safari 10.3, IE 10, Edge 14", type: "MemberExpression", }, ], }, { code: "new PaymentRequest(methodData, details, options)", settings: { browsers: ["chrome 57"] }, errors: [ { message: "PaymentRequest is not supported in Chrome 57", type: "NewExpression", }, ], }, { code: "navigator.serviceWorker", settings: { browsers: ["safari 10.1"] }, errors: [ { message: "navigator.serviceWorker() is not supported in Safari 10.1", type: "MemberExpression", }, ], }, { code: "window.document.fonts()", settings: { browsers: ["ie 8"] }, errors: [ { message: "document.fonts() is not supported in IE 8", type: "MemberExpression", }, ], }, { code: "new Map().size", settings: { browsers: ["ie 8"] }, errors: [ { message: "Map.size() is not supported in IE 8", type: "MemberExpression", }, { message: "Map is not supported in IE 8", type: "NewExpression", }, ], }, { code: "new window.Map().size", settings: { browsers: ["ie 8"] }, errors: [ { message: "Map.size() is not supported in IE 8", type: "MemberExpression", }, { message: "Map is not supported in IE 8", type: "MemberExpression", }, ], }, { code: "new Array().flat", settings: { browsers: ["ie 8"] }, errors: [ { message: "Array.flat() is not supported in IE 8", type: "MemberExpression", }, ], }, { code: "globalThis.fetch()", settings: { browsers: ["ie 11"] }, errors: [ { message: "fetch is not supported in IE 11", type: "MemberExpression", }, ], }, { code: "fetch()", settings: { browsers: ["ie 11"] }, errors: [ { message: "fetch is not supported in IE 11", type: "CallExpression", }, ], }, { code: "Promise.resolve()", settings: { browsers: ["ie 10"] }, errors: [ { message: "Promise.resolve() is not supported in IE 10", type: "MemberExpression", }, ], }, { code: "Promise.all()", settings: { browsers: ["ie 10"] }, errors: [ { message: "Promise.all() is not supported in IE 10", type: "MemberExpression", }, ], }, { code: "Promise.race()", settings: { browsers: ["ie 10"] }, errors: [ { message: "Promise.race() is not supported in IE 10", type: "MemberExpression", }, ], }, { code: "Promise.reject()", settings: { browsers: ["ie 10"] }, errors: [ { message: "Promise.reject() is not supported in IE 10", type: "MemberExpression", }, ], }, { code: "new URL('http://example')", settings: { browsers: ["chrome 31", "safari 7", "firefox 25"], }, errors: [ { message: "URL is not supported in Safari 7, Firefox 25, Chrome 31", type: "NewExpression", }, ], }, { code: "new URLSearchParams()", settings: { browsers: ["chrome 48", "safari 10", "firefox 28"], }, errors: [ { message: "URLSearchParams is not supported in Safari 10, Firefox 28, Chrome 48", type: "NewExpression", }, ], }, { code: "performance.now()", settings: { browsers: ["ie 9"] }, errors: [ { message: "performance.now() is not supported in IE 9", type: "MemberExpression", }, ], }, { code: "new ResizeObserver()", settings: { browsers: ["ie 11", "safari 12"], }, errors: [ { message: "ResizeObserver is not supported in Safari 12, IE 11", }, ], }, // @TODO: Fix this edge case // { // code: `window?.fetch`, // settings: { browsers: ["ie 9"] }, // errors: [ // { // message: "fetch is not supported in IE 9", // }, // ], // }, { code: "Object.entries({}), Object.values({})", settings: { browsers: ["Android >= 4", "iOS >= 7"], }, errors: [ { message: "Object.entries() is not supported in iOS Safari 7.0-7.1", }, { message: "Object.values() is not supported in iOS Safari 7.0-7.1", }, ], }, ], });
the_stack
'use strict'; import {Client, createRestAppClient, expect} from '@loopback/testlab'; import {RoleTypes} from '@sourceloop/core'; import { AuthClientRepository, RefreshTokenRepository, RoleRepository, UserCredentialsRepository, UserLevelPermissionRepository, UserRepository, UserTenantRepository, } from '../../repositories'; import {setupApplication} from './test-helper'; import {TestingApplication} from '../fixtures/application'; describe('Authentication microservice', () => { let app: TestingApplication; let client: Client; let userRepo: UserRepository; let userTenantRepo: UserTenantRepository; let authClientRepository: AuthClientRepository; let userPermissionRepository: UserLevelPermissionRepository; let refreshTokenRepository: RefreshTokenRepository; let userCredentialsRepository: UserCredentialsRepository; let roleRepository: RoleRepository; const useragent = 'test'; const deviceId = 'test'; const useragentName = 'user-agent'; const deviceIdName = 'device_id'; before('setupApplication', async () => { ({app, client} = await setupApplication()); }); after(async () => app.stop()); before(givenUserRepository); before(givenUserTenantRepository); before(givenAuthClientRepository); before(givenUserPermissionRepository); before(givenRefreshTokenRepository); before(givenRoleRepository); before(givenUserCredentialsRepository); before(() => { client = createRestAppClient(app); }); before(setMockData); after(deleteMockData); afterEach(() => { delete process.env.JWT_ISSUER; delete process.env.JWT_SECRET; }); it('gives status 422 for login request with no client credentials', async () => { const reqData = {}; const response = await client.post(`/auth/login`).send(reqData).expect(422); expect(response).to.have.property('error'); }); it('gives status 422 for login request with no user credentials', async () => { const reqData = { clientId: 'web', clientSecret: 'blah', }; const response = await client.post(`/auth/login`).send(reqData).expect(422); expect(response).to.have.property('error'); }); it('gives status 401 for login request with wrong client credentials', async () => { const reqData = { // eslint-disable-next-line client_id: 'web1', // eslint-disable-next-line client_secret: 'blah1', username: 'someuser', password: 'somepassword', }; const response = await client.post(`/auth/login`).send(reqData).expect(401); expect(response).to.have.property('error'); }); it('gives status 401 for login request with wrong user credentials', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'someuser', password: 'somepassword', }; const response = await client.post(`/auth/login`).send(reqData).expect(401); expect(response).to.have.property('error'); }); it('gives status 200 for login request', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; await client.post(`/auth/login`).send(reqData).expect(200); }); it('should return code in response', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); expect(reqForCode.body).to.have.property('code'); }); it('should return refresh token, access token, expires in response', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const response = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }); expect(response.body).to.have.properties([ 'accessToken', 'refreshToken', 'expires', ]); }); it('should return 401 for incorrect moment creation', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; await client .post(`/auth/login-token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send(reqData) .expect(401); }); it('should change password successfully', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client.post(`/auth/token`).send({ clientId: 'web', code: reqForCode.body.code, }); await client .patch(`/auth/change-password`) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`) .send({ username: 'test_user', password: 'new_test_password', refreshToken: reqForToken.body.refreshToken, }) .expect(200); }); it('should return refresh token and access token for token refresh request', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'new_test_password', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }); const response = await client .post(`/auth/token-refresh`) .send({refreshToken: reqForToken.body.refreshToken}) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`); expect(response.body).to.have.properties(['accessToken', 'refreshToken']); }); it('should return 401 for token refresh request when Authentication token invalid', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }); await client .post(`/auth/token-refresh`) .send({refreshToken: reqForToken.body.refreshToken}) .set('Authorization', 'Bearer abc') .expect(401); }); it('should return 401 for token refresh request when Authentication token missing', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'temp123!@', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }); await client .post(`/auth/token-refresh`) .send({refreshToken: reqForToken.body.refreshToken}) .expect(401); }); it('should send forgot password request successfully', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const response = await client .post(`/auth/forget-password`) .send(reqData) .expect(200); expect(response.body).to.have.properties(['code']); }); it('should return error user does not exist', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'testuser', }; const response = await client .post(`/auth/forget-password`) .send(reqData) .expect(404); expect(response.body).to.have.properties('error'); }); it('should verify token successfully', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const response = await client .post(`/auth/forget-password`) .send(reqData) .expect(200); const responseToken = await client .get(`/auth/verify-reset-password-link?token=${response.body.code}`) .send() .expect(200); expect(responseToken.body).to.have.properties('success'); }); it('should give token missing error', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; await client.post(`/auth/forget-password`).send(reqData).expect(200); const responseToken = await client .get(`/auth/verify-reset-password-link`) .send() .expect(400); expect(responseToken.body).to.have.properties('error'); }); it('return error for token missing', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; await client.post(`/auth/forget-password`).send(reqData).expect(200); const request = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', password: 'test123', }; await client.patch(`/auth/reset-password`).send(request).expect(422); }); it('return error for password missing', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const response = await client .post(`/auth/forget-password`) .send(reqData) .expect(200); const request = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', token: response.body.code, }; await client.patch(`/auth/reset-password`).send(request).expect(422); }); it('should reset password', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const response = await client .post(`/auth/forget-password`) .send(reqData) .expect(200); const request = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', token: response.body.code, password: 'test123', }; await client.patch(`/auth/reset-password`).send(request).expect(204); }); it('should return true on logout', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'test123', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }) .expect(200); await client .post(`/logout`) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`) .send({ refreshToken: reqForToken.body.refreshToken, }) .expect(200); }); it('should return error for wrong token on logout', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'test123', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }) .expect(200); await client .post(`/logout`) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`) .send({ refreshToken: 'aaaa', }) .expect(401); }); it('should return true on keycloak logout', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'test123', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }) .expect(200); await client .post(`/keycloak/logout`) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`) .send({ refreshToken: reqForToken.body.refreshToken, }) .expect(200); }); it('should return error for wrong token on keycloak logout', async () => { const reqData = { // eslint-disable-next-line client_id: 'web', // eslint-disable-next-line client_secret: 'test', username: 'test_user', password: 'test123', }; process.env.JWT_ISSUER = 'test'; process.env.JWT_SECRET = 'test'; const reqForCode = await client .post(`/auth/login`) .send(reqData) .expect(200); const reqForToken = await client .post(`/auth/token`) .set(deviceIdName, deviceId) .set(useragentName, useragent) .send({ clientId: 'web', code: reqForCode.body.code, }) .expect(200); await client .post(`/keycloak/logout`) .set('Authorization', `Bearer ${reqForToken.body.accessToken}`) .send({ refreshToken: 'aaaa', }) .expect(401); }); async function givenUserRepository() { userRepo = await app.getRepository(UserRepository); } async function givenUserTenantRepository() { userTenantRepo = await app.getRepository(UserTenantRepository); } async function givenRoleRepository() { roleRepository = await app.getRepository(RoleRepository); } async function givenAuthClientRepository() { authClientRepository = await app.getRepository(AuthClientRepository); } async function givenUserPermissionRepository() { userPermissionRepository = await app.getRepository( UserLevelPermissionRepository, ); } async function givenUserCredentialsRepository() { userCredentialsRepository = await app.getRepository( UserCredentialsRepository, ); } async function givenRefreshTokenRepository() { refreshTokenRepository = await app.getRepository(RefreshTokenRepository); } async function deleteMockData() { await userCredentialsRepository.deleteAllHard(); await userPermissionRepository.deleteAllHard(); await userRepo.deleteAllHard(); await authClientRepository.deleteAllHard(); await refreshTokenRepository.deleteAll(); await roleRepository.deleteAllHard(); } async function setMockData() { await roleRepository.createAll([ { id: '1', name: 'admin', roleType: RoleTypes.Admin, permissions: [ 'canLoginToIPS', 'ViewOwnUser', 'ViewAnyUser', 'ViewTenantUser', 'CreateAnyUser', 'CreateTenantUser', 'UpdateOwnUser', 'UpdateTenantUser', 'UpdateAnyUser', 'DeleteTenantUser', 'DeleteAnyUser', 'ViewTenant', 'CreateTenant', 'UpdateTenant', 'DeleteTenant', 'ViewRole', 'CreateRole', 'UpdateRole', 'DeleteRole', 'ViewAudit', 'CreateAudit', 'UpdateAudit', 'DeleteAudit', ], }, { id: '2', name: 'others', roleType: RoleTypes.Others, permissions: [ 'ViewOwnUser', 'ViewTenantUser', 'CreateTenantUser', 'UpdateOwnUser', 'UpdateTenantUser', 'DeleteTenantUser', 'ViewTenant', 'ViewRole', ], }, ]); await userRepo.createAll([ { id: '1', firstName: 'Test', lastName: 'User', username: 'test_user', dob: '1996-11-05', authClientIds: `{1}`, email: 'xyz@gmail.com', }, { id: '2', firstName: 'Test', lastName: 'Teacher', username: 'test_teacher', dob: '1996-11-05', authClientIds: `{1}`, }, ]); await userTenantRepo.create( { userId: '1', tenantId: '200', roleId: '2', }, { userId: '2', tenantId: '200', roleId: '2', }, ); await authClientRepository.create({ id: 1, clientId: 'web', clientSecret: 'test', redirectUrl: 'http://localhost:4200/login/success', accessTokenExpiration: 900, refreshTokenExpiration: 86400, authCodeExpiration: 180, secret: 'poiuytrewq', }); await userCredentialsRepository.create({ id: '1', userId: '1', authProvider: 'test_auth', password: 'temp123!@', }); } });
the_stack
import 'jest'; import { call, put } from 'redux-saga/effects'; // tslint:disable-next-line: no-implicit-dependencies import { SagaIteratorClone, cloneableGenerator } from '@redux-saga/testing-utils'; import { getModelDefinitionSaga, getModelDefinition, getModelDefinitionFromPublicRepo, getModelDefinitionFromLocalFile, validateModelDefinitionHelper, getFlattenedModel, getModelDefinitionFromConfigurableRepo } from './getModelDefinitionSaga'; import { raiseNotificationToast } from '../../../notifications/components/notificationToast'; import { NotificationType } from '../../../api/models/notification'; import { ResourceKeys } from '../../../../localization/resourceKeys'; import { getModelDefinitionAction, GetModelDefinitionActionParameters } from '../actions'; import { REPOSITORY_LOCATION_TYPE } from '../../../constants/repositoryLocationTypes'; import { fetchLocalFile } from '../../../api/services/localRepoService'; import { fetchModelDefinition } from '../../../api/services/publicDigitalTwinsModelRepoService'; import { ModelDefinition } from './../../../api/models/modelDefinition'; describe('modelDefinition sagas', () => { describe('modelDefinition saga flow with no inline component', () => { const digitalTwinId = 'device_id'; const interfaceId = 'urn:azureiot:ModelDiscovery:DigitalTwin:1'; const params: GetModelDefinitionActionParameters = { digitalTwinId, interfaceId, locations: [{ repositoryLocationType: REPOSITORY_LOCATION_TYPE.Public }], }; const action = getModelDefinitionAction.started(params); /* tslint:disable */ const modelDefinition = { "@id": "urn:azureiot:ModelDiscovery:DigitalTwin:1", "@type": "Interface", "contents": [ { "@type": "Property", "name": "modelInformation", "displayName": "Model Information", "description": "Providing model and optional interfaces information on a digital twin.", "schema": { "@type": "Object", "fields": [ { "name": "modelId", "schema": "string" }, { "name": "interfaces", "schema": { "@type": "Map", "mapKey": { "name": "name", "schema": "string" }, "mapValue": { "name": "schema", "schema": "string" } } } ] } } ], "@context": "http://azureiot.com/v1/contexts/Interface.json" }; /* tslint:enable */ describe('getModelDefinitionSaga', () => { let getModelDefinitionSagaGenerator: SagaIteratorClone; beforeAll(() => { getModelDefinitionSagaGenerator = cloneableGenerator(getModelDefinitionSaga)(action); }); it('fetches the model definition', () => { expect(getModelDefinitionSagaGenerator.next().value).toEqual( call(getModelDefinition, action, { repositoryLocationType: REPOSITORY_LOCATION_TYPE.Public }) ); expect(getModelDefinitionSagaGenerator.next(modelDefinition).value).toEqual( call(validateModelDefinitionHelper, modelDefinition, { repositoryLocationType: REPOSITORY_LOCATION_TYPE.Public }) ); }); it('puts the successful action', () => { const success = getModelDefinitionSagaGenerator.clone(); expect(success.next(true)).toEqual({ done: false, value: put((getModelDefinitionAction.done({ params, result: { isModelValid: true, modelDefinition, source: REPOSITORY_LOCATION_TYPE.Public } }))) }); expect(success.next().done).toEqual(true); }); it('fails on error', () => { const failure = getModelDefinitionSagaGenerator.clone(); expect(failure.throw()).toEqual({ done: false, value: call(raiseNotificationToast, { text: { translationKey: ResourceKeys.notifications.getInterfaceModelOnError, translationOptions: { interfaceId: params.interfaceId }, }, type: NotificationType.error, }) }); expect(failure.next()).toEqual({ done: false, value: put(getModelDefinitionAction.failed({ error: undefined, params })) }); expect(failure.next().done).toEqual(true); }); }); describe('getModelDefinitionFromPublicRepo ', () => { const getModelDefinitionFromPublicRepoGenerator = cloneableGenerator(getModelDefinitionFromPublicRepo)(action); expect(getModelDefinitionFromPublicRepoGenerator.next([action.payload.interfaceId])).toEqual({ done: false, value: call(fetchModelDefinition, { id: action.payload.interfaceId, token: '' }) }); expect(getModelDefinitionFromPublicRepoGenerator.next(modelDefinition).done).toEqual(true); }); describe('getModelDefinitionFromLocalFile ', () => { const getModelDefinitionFromLocalFolderGenerator = cloneableGenerator(getModelDefinitionFromLocalFile) (action); expect(getModelDefinitionFromLocalFolderGenerator.next([action.payload.interfaceId])).toEqual({ done: false, value: call(fetchLocalFile, '', action.payload.interfaceId) }); expect(getModelDefinitionFromLocalFolderGenerator.next(modelDefinition).done).toEqual(true); }); describe('getModelDefinition', () => { it('getModelDefinition from public repo', () => { const getModelDefinitionFromPublicRepoGenerator = cloneableGenerator(getModelDefinition)(action, {repositoryLocationType: REPOSITORY_LOCATION_TYPE.Public}); expect(getModelDefinitionFromPublicRepoGenerator.next()).toEqual({ done: false, value: call(getModelDefinitionFromPublicRepo, action) }); expect(getModelDefinitionFromPublicRepoGenerator.next().done).toEqual(true); }); it('getModelDefinition from local', () => { const getModelDefinitionFromDeviceGenerator = cloneableGenerator(getModelDefinition)(action, {repositoryLocationType: REPOSITORY_LOCATION_TYPE.Local}); expect(getModelDefinitionFromDeviceGenerator.next()).toEqual({ done: false, value: call(getModelDefinitionFromLocalFile, action) }); expect(getModelDefinitionFromDeviceGenerator.next().done).toEqual(true); }); }); describe('getFlattenedModel ', () => { expect(getFlattenedModel(modelDefinition, [interfaceId])).toEqual(modelDefinition); }); }); describe('modelDefinition saga flow with inline component', () => { const digitalTwinId = 'device_id'; const interfaceId = 'urn:azureiot:ModelDiscovery:DigitalTwin:1'; const schemaId = 'dtmi:com:rido:inlineTests:inlineComp;2'; const fullInterfaceId = `${interfaceId}/${schemaId}`; const params: GetModelDefinitionActionParameters = { digitalTwinId, interfaceId: fullInterfaceId, locations: [{ repositoryLocationType: REPOSITORY_LOCATION_TYPE.Public }], }; const action = getModelDefinitionAction.started(params); /* tslint:disable */ const modelDefinition: ModelDefinition = { "@context": "dtmi:dtdl:context;2", "@id": "urn:azureiot:ModelDiscovery:DigitalTwin:1", "@type": "Interface", "contents": [ { "@id": "dtmi:com:rido:inlineComp;2", "@type": "Component", "name": "inLineComponent", "schema": { "@type": "Interface", "@id": schemaId, "contents": [ { "@type" : "Property", "name" : "inlineProp", "schema" : "string" } ] } } ] }; /* tslint:enable */ describe('getModelDefinitionFromPublicRepo ', () => { const getModelDefinitionFromPublicRepoGenerator = cloneableGenerator(getModelDefinitionFromPublicRepo)(action); expect(getModelDefinitionFromPublicRepoGenerator.next([interfaceId, schemaId])).toEqual({ done: false, value: call(fetchModelDefinition, { id: interfaceId, token: '' }) }); expect(getModelDefinitionFromPublicRepoGenerator.next(modelDefinition).done).toEqual(true); }); describe('getModelDefinitionFromLocalFile ', () => { const getModelDefinitionFromLocalFolderGenerator = cloneableGenerator(getModelDefinitionFromLocalFile) (getModelDefinitionAction.started({ digitalTwinId, interfaceId, locations: [{ repositoryLocationType: REPOSITORY_LOCATION_TYPE.Local, value: 'f:' }], })); expect(getModelDefinitionFromLocalFolderGenerator.next([interfaceId, schemaId])).toEqual({ done: false, value: call(fetchLocalFile, 'f:', interfaceId) }); expect(getModelDefinitionFromLocalFolderGenerator.next(modelDefinition).done).toEqual(true); }); describe('getModelDefinitionFromConfigurableRepo ', () => { const getModelDefinitionFromConfigurableRepoGenerator = cloneableGenerator(getModelDefinitionFromConfigurableRepo) (getModelDefinitionAction.started({ digitalTwinId, interfaceId, locations: [{ repositoryLocationType: REPOSITORY_LOCATION_TYPE.Configurable, value: 'devicemodeltest.azureedge.net' }], })); expect(getModelDefinitionFromConfigurableRepoGenerator.next([interfaceId, schemaId])).toEqual({ done: false, value: call(fetchModelDefinition, { id: interfaceId, token: '', url: 'devicemodeltest.azureedge.net' }) }); expect(getModelDefinitionFromConfigurableRepoGenerator.next(modelDefinition).done).toEqual(true); }); describe('getFlattenedModel ', () => { expect(getFlattenedModel(modelDefinition, [interfaceId, schemaId])).toEqual(modelDefinition.contents[0]); }); }); });
the_stack
import { program } from 'commander'; import log from 'loglevel'; import { getAtaForMint, getMasterEdition, getMetadata, getTokenAmount, getTokenEntanglement, getTokenEntanglementEscrows, loadTokenEntanglementProgream, loadWalletKey, } from './helpers/accounts'; import { BN, web3, Program } from '@project-serum/anchor'; import { TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT } from './helpers/constants'; import { ASSOCIATED_TOKEN_PROGRAM_ID, Token } from '@solana/spl-token'; import { getPriceWithMantissa } from './helpers/various'; import { sendTransactionWithRetryWithKeypair } from './helpers/transactions'; import { decodeMetadata, Metadata } from './helpers/schema'; program.version('0.0.1'); log.setLevel('info'); export const getEpKeyFromArgs = async ( anchorProgram: Program, mintA: web3.PublicKey | null, mintB: web3.PublicKey | null, entangledPair: string | undefined, ): Promise<web3.PublicKey> => { let epKey; if (!entangledPair) { log.info('No entangled pair detected, generating from mint arguments.'); epKey = (await getTokenEntanglement(mintA, mintB))[0]; const obj = await anchorProgram.provider.connection.getAccountInfo(epKey); if (!obj) { epKey = (await getTokenEntanglement(mintB, mintA))[0]; } } else { epKey = new web3.PublicKey(entangledPair); } return epKey; }; programCommand('show') .option( '-ep, --entangled-pair <string>', 'Optional. Overrides mint arguments.', ) .option('-ma, --mint-a <string>', 'mint a') .option('-mb, --mint-b <string>', 'mint b') .action(async (directory, cmd) => { const { keypair, env, entangledPair, mintA, mintB } = cmd.opts(); const walletKeyPair = loadWalletKey(keypair); const anchorProgram = await loadTokenEntanglementProgream( walletKeyPair, env, ); const epKey = await getEpKeyFromArgs( anchorProgram, mintA ? new web3.PublicKey(mintA) : null, mintB ? new web3.PublicKey(mintB) : null, entangledPair, ); const epObj = await anchorProgram.account.entangledPair.fetch(epKey); log.info('-----'); log.info('Entangled Pair:', epKey.toBase58()); //@ts-ignore log.info('Mint:', epObj.treasuryMint.toBase58()); //@ts-ignore log.info('Authority:', epObj.authority.toBase58()); //@ts-ignore log.info('Mint A:', epObj.mintA.toBase58()); //@ts-ignore log.info('Mint B:', epObj.mintB.toBase58()); //@ts-ignore log.info('Token A Escrow:', epObj.tokenAEscrow.toBase58()); //@ts-ignore log.info('Token B Escrow:', epObj.tokenBEscrow.toBase58()); //@ts-ignore log.info('Price:', epObj.price.toNumber()); //@ts-ignore log.info('Paid At Least Once:', epObj.paid); //@ts-ignore log.info('Pays Every Time:', epObj.paysEveryTime); //@ts-ignore log.info('Bump:', epObj.bump); }); programCommand('create_entanglement') .option( '-tm, --treasury-mint <string>', 'Mint address of treasury. If not used, default to SOL.', ) .option('-a, --authority <string>', 'Authority, defaults to keypair') .option('-p, --price <string>', 'Price for a swap') .option( '-pet, --pays-every-time <string>', 'If true, the user must pay the swapping fee each swap', ) .option( '-ma, --mint-a <string>', 'Mint a. You do not even need to own this token to create this entanglement.', ) .option( '-mb, --mint-b <string>', 'Mint b. This token will be removed from your token account right now.', ) // eslint-disable-next-line @typescript-eslint/no-unused-vars .action(async (directory, cmd) => { const { keypair, env, price, paysEveryTime, mintA, mintB, treasuryMint, authority, } = cmd.opts(); const priceNumber = parseFloat(price); const walletKeyPair = loadWalletKey(keypair); const anchorProgram = await loadTokenEntanglementProgream( walletKeyPair, env, ); let authorityKey: web3.PublicKey, tMintKey: web3.PublicKey; if (!authority) { log.info('No authority detected, using keypair'); authorityKey = walletKeyPair.publicKey; } else { authorityKey = new web3.PublicKey(authority); } const mintAKey = new web3.PublicKey(mintA); const mintBKey = new web3.PublicKey(mintB); if (!treasuryMint) { log.info('No treasury mint detected, using SOL.'); tMintKey = WRAPPED_SOL_MINT; } else { tMintKey = new web3.PublicKey(treasuryMint); } const [entangledPair, bump] = await getTokenEntanglement( mintAKey, mintBKey, ); const [reverseEntangledPair, reverseBump] = await getTokenEntanglement( mintBKey, mintAKey, ); const [tokenAEscrow, tokenABump, tokenBEscrow, tokenBBump] = await getTokenEntanglementEscrows(mintAKey, mintBKey); const priceAdjusted = new BN( await getPriceWithMantissa( priceNumber, tMintKey, walletKeyPair, anchorProgram, ), ); const ata = (await getAtaForMint(mintBKey, walletKeyPair.publicKey))[0]; const transferAuthority = web3.Keypair.generate(); const signers = [transferAuthority]; const instruction = await anchorProgram.instruction.createEntangledPair( bump, reverseBump, tokenABump, tokenBBump, priceAdjusted, paysEveryTime == 'true', { accounts: { treasuryMint: tMintKey, payer: walletKeyPair.publicKey, transferAuthority: transferAuthority.publicKey, authority: authorityKey, mintA: mintAKey, metadataA: await getMetadata(mintAKey), editionA: await getMasterEdition(mintAKey), mintB: mintBKey, metadataB: await getMetadata(mintBKey), editionB: await getMasterEdition(mintBKey), tokenB: ata, tokenAEscrow, tokenBEscrow, entangledPair, reverseEntangledPair, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: web3.SystemProgram.programId, rent: web3.SYSVAR_RENT_PUBKEY, }, }, ); const instructions = [ Token.createApproveInstruction( TOKEN_PROGRAM_ID, ata, transferAuthority.publicKey, walletKeyPair.publicKey, [], 1, ), instruction, Token.createRevokeInstruction( TOKEN_PROGRAM_ID, ata, walletKeyPair.publicKey, [], ), ]; await sendTransactionWithRetryWithKeypair( anchorProgram.provider.connection, walletKeyPair, instructions, signers, 'max', ); log.info('Created entanglement', entangledPair.toBase58()); }); programCommand('swap') .option( '-ep, --entangled-pair <string>', 'Optional. Overrides mint arguments.', ) .option( '-ma, --mint-a <string>', 'Mint a. You do not even need to own this token to create this entanglement.', ) .option( '-mb, --mint-b <string>', 'Mint b. This token will be removed from your token account right now.', ) // eslint-disable-next-line @typescript-eslint/no-unused-vars .action(async (directory, cmd) => { const { keypair, env, mintA, mintB, entangledPair } = cmd.opts(); const walletKeyPair = loadWalletKey(keypair); const anchorProgram = await loadTokenEntanglementProgream( walletKeyPair, env, ); const epKey = await getEpKeyFromArgs( anchorProgram, mintA ? new web3.PublicKey(mintA) : null, mintB ? new web3.PublicKey(mintB) : null, entangledPair, ); const epObj = await anchorProgram.account.entangledPair.fetch(epKey); //@ts-ignore const mintAKey = epObj.mintA; //@ts-ignore const mintBKey = epObj.mintB; const aAta = (await getAtaForMint(mintAKey, walletKeyPair.publicKey))[0]; const bAta = (await getAtaForMint(mintBKey, walletKeyPair.publicKey))[0]; const currABal = await getTokenAmount(anchorProgram, aAta, mintAKey); const token = currABal == 1 ? aAta : bAta, replacementToken = currABal == 1 ? bAta : aAta; const tokenMint = currABal == 1 ? mintAKey : mintBKey, replacementTokenMint = currABal == 1 ? mintBKey : mintAKey; const result = await getTokenEntanglementEscrows(mintAKey, mintBKey); const tokenAEscrow = result[0]; const tokenBEscrow = result[2]; const transferAuthority = web3.Keypair.generate(); const paymentTransferAuthority = web3.Keypair.generate(); const replacementTokenMetadata = await getMetadata(replacementTokenMint); const signers = [transferAuthority]; //@ts-ignore const isNative = epObj.treasuryMint.equals(WRAPPED_SOL_MINT); //@ts-ignore const paymentAccount = isNative ? walletKeyPair.publicKey : (await getAtaForMint(epObj.treasuryMint, walletKeyPair.publicKey))[0]; if (!isNative) signers.push(paymentTransferAuthority); const remainingAccounts = []; const metadataObj = await anchorProgram.provider.connection.getAccountInfo( replacementTokenMetadata, ); const metadataDecoded: Metadata = decodeMetadata( Buffer.from(metadataObj.data), ); for (let i = 0; i < metadataDecoded.data.creators.length; i++) { remainingAccounts.push({ pubkey: new web3.PublicKey(metadataDecoded.data.creators[i].address), isWritable: true, isSigner: false, }); if (!isNative) { remainingAccounts.push({ pubkey: ( await getAtaForMint( //@ts-ignore epObj.treasuryMint, remainingAccounts[remainingAccounts.length - 1].pubkey, ) )[0], isWritable: true, isSigner: false, }); } } const instruction = await anchorProgram.instruction.swap({ accounts: { //@ts-ignore treasuryMint: epObj.treasuryMint, payer: walletKeyPair.publicKey, paymentAccount, transferAuthority: transferAuthority.publicKey, paymentTransferAuthority: paymentTransferAuthority.publicKey, token, replacementTokenMetadata, replacementToken, replacementTokenMint, tokenAEscrow, tokenBEscrow, entangledPair: epKey, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: web3.SystemProgram.programId, ataProgram: ASSOCIATED_TOKEN_PROGRAM_ID, rent: web3.SYSVAR_RENT_PUBKEY, }, remainingAccounts, }); if (!isNative) { instruction.keys .filter(k => k.pubkey.equals(paymentTransferAuthority.publicKey)) .map(k => (k.isSigner = true)); } const instructions = [ Token.createApproveInstruction( TOKEN_PROGRAM_ID, token, transferAuthority.publicKey, walletKeyPair.publicKey, [], 1, ), ...(!isNative ? [ Token.createApproveInstruction( TOKEN_PROGRAM_ID, paymentAccount, paymentTransferAuthority.publicKey, walletKeyPair.publicKey, [], //@ts-ignore epObj.price.toNumber(), ), ] : []), instruction, Token.createRevokeInstruction( TOKEN_PROGRAM_ID, token, walletKeyPair.publicKey, [], ), ...(!isNative ? [ Token.createRevokeInstruction( TOKEN_PROGRAM_ID, paymentAccount, walletKeyPair.publicKey, [], ), ] : []), ]; await sendTransactionWithRetryWithKeypair( anchorProgram.provider.connection, walletKeyPair, instructions, signers, 'max', ); log.info( 'Swapped', tokenMint.toBase58(), 'mint for', replacementTokenMint.toBase58(), ' with entangled pair ', epKey.toBase58(), ); }); programCommand('update_entanglement') .option( '-ep, --entangled-pair <string>', 'Optional. Overrides mint arguments.', ) .option('-na, --new-authority <string>', 'Authority, defaults to keypair') .option('-p, --price <string>', 'Price for a swap') .option( '-pet, --pays-every-time <string>', 'If true, the user must pay the swapping fee each swap', ) .option( '-ma, --mint-a <string>', 'Mint a. You do not even need to own this token to create this entanglement.', ) .option( '-mb, --mint-b <string>', 'Mint b. This token will be removed from your token account right now.', ) // eslint-disable-next-line @typescript-eslint/no-unused-vars .action(async (directory, cmd) => { const { keypair, env, price, paysEveryTime, mintA, mintB, entangledPair, newAuthority, } = cmd.opts(); const walletKeyPair = loadWalletKey(keypair); const anchorProgram = await loadTokenEntanglementProgream( walletKeyPair, env, ); const epKey = await getEpKeyFromArgs( anchorProgram, mintA ? new web3.PublicKey(mintA) : null, mintB ? new web3.PublicKey(mintB) : null, entangledPair, ); const epObj = await anchorProgram.account.entangledPair.fetch(epKey); //@ts-ignore const authorityKey = new web3.PublicKey( newAuthority ? newAuthority : epObj.authority, ); const priceAdjusted = price ? new BN( await getPriceWithMantissa( parseFloat(price), //@ts-ignore epObj.treasuryMint, walletKeyPair, anchorProgram, ), ) : //@ts-ignore epObj.price; await anchorProgram.rpc.updateEntangledPair( priceAdjusted, paysEveryTime == 'true', { accounts: { newAuthority: authorityKey, //@ts-ignore authority: epObj.authority, entangledPair: epKey, }, }, ); log.info('Updated entanglement', epKey.toBase58()); }); function programCommand(name: string) { return program .command(name) .option( '-e, --env <string>', 'Solana cluster env name', 'devnet', //mainnet-beta, testnet, devnet ) .option( '-k, --keypair <path>', `Solana wallet location`, '--keypair not provided', ) .option('-l, --log-level <string>', 'log level', setLogLevel); } // eslint-disable-next-line @typescript-eslint/no-unused-vars function setLogLevel(value, prev) { if (value === undefined || value === null) { return; } log.info('setting the log value to: ' + value); log.setLevel(value); } program.parse(process.argv);
the_stack
import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { RunOnceScheduler } from 'vs/base/common/async'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { asCssVariableName } from 'vs/platform/theme/common/colorRegistry'; import { ThemeColor } from 'vs/platform/theme/common/themeService'; /** * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY) */ export class PageCoordinates { _pageCoordinatesBrand: void = undefined; constructor( public readonly x: number, public readonly y: number ) { } public toClientCoordinates(): ClientCoordinates { return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.scrollY); } } /** * Coordinates within the application's client area (i.e. origin is document's scroll position). * * For example, clicking in the top-left corner of the client area will * always result in a mouse event with a client.x value of 0, regardless * of whether the page is scrolled horizontally. */ export class ClientCoordinates { _clientCoordinatesBrand: void = undefined; constructor( public readonly clientX: number, public readonly clientY: number ) { } public toPageCoordinates(): PageCoordinates { return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.scrollY); } } /** * The position of the editor in the page. */ export class EditorPagePosition { _editorPagePositionBrand: void = undefined; constructor( public readonly x: number, public readonly y: number, public readonly width: number, public readonly height: number ) { } } /** * Coordinates relative to the the (top;left) of the editor that can be used safely with other internal editor metrics. * **NOTE**: This position is obtained by taking page coordinates and transforming them relative to the * editor's (top;left) position in a way in which scale transformations are taken into account. * **NOTE**: These coordinates could be negative if the mouse position is outside the editor. */ export class CoordinatesRelativeToEditor { _positionRelativeToEditorBrand: void = undefined; constructor( public readonly x: number, public readonly y: number ) { } } export function createEditorPagePosition(editorViewDomNode: HTMLElement): EditorPagePosition { const editorPos = dom.getDomNodePagePosition(editorViewDomNode); return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height); } export function createCoordinatesRelativeToEditor(editorViewDomNode: HTMLElement, editorPagePosition: EditorPagePosition, pos: PageCoordinates) { // The editor's page position is read from the DOM using getBoundingClientRect(). // // getBoundingClientRect() returns the actual dimensions, while offsetWidth and offsetHeight // reflect the unscaled size. We can use this difference to detect a transform:scale() // and we will apply the transformation in inverse to get mouse coordinates that make sense inside the editor. // // This could be expanded to cover rotation as well maybe by walking the DOM up from `editorViewDomNode` // and computing the effective transformation matrix using getComputedStyle(element).transform. // const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth; const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight; // Adjust mouse offsets if editor appears to be scaled via transforms const relativeX = (pos.x - editorPagePosition.x) / scaleX; const relativeY = (pos.y - editorPagePosition.y) / scaleY; return new CoordinatesRelativeToEditor(relativeX, relativeY); } export class EditorMouseEvent extends StandardMouseEvent { _editorMouseEventBrand: void = undefined; /** * If the event is a result of using `setPointerCapture`, the `event.target` * does not necessarily reflect the position in the editor. */ public readonly isFromPointerCapture: boolean; /** * Coordinates relative to the whole document. */ public readonly pos: PageCoordinates; /** * Editor's coordinates relative to the whole document. */ public readonly editorPos: EditorPagePosition; /** * Coordinates relative to the (top;left) of the editor. * *NOTE*: These coordinates are preferred because they take into account transformations applied to the editor. * *NOTE*: These coordinates could be negative if the mouse position is outside the editor. */ public readonly relativePos: CoordinatesRelativeToEditor; constructor(e: MouseEvent, isFromPointerCapture: boolean, editorViewDomNode: HTMLElement) { super(e); this.isFromPointerCapture = isFromPointerCapture; this.pos = new PageCoordinates(this.posx, this.posy); this.editorPos = createEditorPagePosition(editorViewDomNode); this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos); } } export class EditorMouseEventFactory { private readonly _editorViewDomNode: HTMLElement; constructor(editorViewDomNode: HTMLElement) { this._editorViewDomNode = editorViewDomNode; } private _create(e: MouseEvent): EditorMouseEvent { return new EditorMouseEvent(e, false, this._editorViewDomNode); } public onContextMenu(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'contextmenu', (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseUp(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'mouseup', (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseDown(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, dom.EventType.MOUSE_DOWN, (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerDown(target: HTMLElement, callback: (e: EditorMouseEvent, pointerId: number) => void): IDisposable { return dom.addDisposableListener(target, dom.EventType.POINTER_DOWN, (e: PointerEvent) => { callback(this._create(e), e.pointerId); }); } public onMouseLeave(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableNonBubblingMouseOutListener(target, (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseMove(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'mousemove', (e) => callback(this._create(e))); } } export class EditorPointerEventFactory { private readonly _editorViewDomNode: HTMLElement; constructor(editorViewDomNode: HTMLElement) { this._editorViewDomNode = editorViewDomNode; } private _create(e: MouseEvent): EditorMouseEvent { return new EditorMouseEvent(e, false, this._editorViewDomNode); } public onPointerUp(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'pointerup', (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerDown(target: HTMLElement, callback: (e: EditorMouseEvent, pointerId: number) => void): IDisposable { return dom.addDisposableListener(target, dom.EventType.POINTER_DOWN, (e: PointerEvent) => { callback(this._create(e), e.pointerId); }); } public onPointerLeave(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableNonBubblingPointerOutListener(target, (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerMove(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'pointermove', (e) => callback(this._create(e))); } } export class GlobalEditorPointerMoveMonitor extends Disposable { private readonly _editorViewDomNode: HTMLElement; private readonly _globalPointerMoveMonitor: GlobalPointerMoveMonitor; private _keydownListener: IDisposable | null; constructor(editorViewDomNode: HTMLElement) { super(); this._editorViewDomNode = editorViewDomNode; this._globalPointerMoveMonitor = this._register(new GlobalPointerMoveMonitor()); this._keydownListener = null; } public startMonitoring( initialElement: Element, pointerId: number, initialButtons: number, pointerMoveCallback: (e: EditorMouseEvent) => void, onStopCallback: (browserEvent?: PointerEvent | KeyboardEvent) => void ): void { // Add a <<capture>> keydown event listener that will cancel the monitoring // if something other than a modifier key is pressed this._keydownListener = dom.addStandardDisposableListener(<any>document, 'keydown', (e) => { const kb = e.toKeybinding(); if (kb.isModifierKey()) { // Allow modifier keys return; } this._globalPointerMoveMonitor.stopMonitoring(true, e.browserEvent); }, true); this._globalPointerMoveMonitor.startMonitoring( initialElement, pointerId, initialButtons, (e) => { pointerMoveCallback(new EditorMouseEvent(e, true, this._editorViewDomNode)); }, (e) => { this._keydownListener!.dispose(); onStopCallback(e); } ); } public stopMonitoring(): void { this._globalPointerMoveMonitor.stopMonitoring(true); } } /** * A helper to create dynamic css rules, bound to a class name. * Rules are reused. * Reference counting and delayed garbage collection ensure that no rules leak. */ export class DynamicCssRules { private static _idPool = 0; private readonly _instanceId = ++DynamicCssRules._idPool; private _counter = 0; private readonly _rules = new Map<string, RefCountedCssRule>(); // We delay garbage collection so that hanging rules can be reused. private readonly _garbageCollectionScheduler = new RunOnceScheduler(() => this.garbageCollect(), 1000); constructor(private readonly _editor: ICodeEditor) { } public createClassNameRef(options: CssProperties): ClassNameReference { const rule = this.getOrCreateRule(options); rule.increaseRefCount(); return { className: rule.className, dispose: () => { rule.decreaseRefCount(); this._garbageCollectionScheduler.schedule(); } }; } private getOrCreateRule(properties: CssProperties): RefCountedCssRule { const key = this.computeUniqueKey(properties); let existingRule = this._rules.get(key); if (!existingRule) { const counter = this._counter++; existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, dom.isInShadowDOM(this._editor.getContainerDomNode()) ? this._editor.getContainerDomNode() : undefined, properties ); this._rules.set(key, existingRule); } return existingRule; } private computeUniqueKey(properties: CssProperties): string { return JSON.stringify(properties); } private garbageCollect() { for (const rule of this._rules.values()) { if (!rule.hasReferences()) { this._rules.delete(rule.key); rule.dispose(); } } } } export interface ClassNameReference extends IDisposable { className: string; } export interface CssProperties { border?: string; borderColor?: string | ThemeColor; borderRadius?: string; fontStyle?: string; fontWeight?: string; fontSize?: string; fontFamily?: string; textDecoration?: string; color?: string | ThemeColor; backgroundColor?: string | ThemeColor; opacity?: string; verticalAlign?: string; cursor?: string; margin?: string; padding?: string; width?: string; height?: string; display?: string; } class RefCountedCssRule { private _referenceCount: number = 0; private _styleElement: HTMLStyleElement; constructor( public readonly key: string, public readonly className: string, _containerElement: HTMLElement | undefined, public readonly properties: CssProperties, ) { this._styleElement = dom.createStyleSheet( _containerElement ); this._styleElement.textContent = this.getCssText(this.className, this.properties); } private getCssText(className: string, properties: CssProperties): string { let str = `.${className} {`; for (const prop in properties) { const value = (properties as any)[prop] as string | ThemeColor; let cssValue; if (typeof value === 'object') { cssValue = `var(${asCssVariableName(value.id)})`; } else { cssValue = value; } const cssPropName = camelToDashes(prop); str += `\n\t${cssPropName}: ${cssValue};`; } str += `\n}`; return str; } public dispose(): void { this._styleElement.remove(); } public increaseRefCount(): void { this._referenceCount++; } public decreaseRefCount(): void { this._referenceCount--; } public hasReferences(): boolean { return this._referenceCount > 0; } } function camelToDashes(str: string): string { return str.replace(/(^[A-Z])/, ([first]) => first.toLowerCase()) .replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`); }
the_stack
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { HtmlEscaperService } from 'services/html-escaper.service'; import { NoninteractiveImage } from './oppia-noninteractive-image.component'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ContextService } from 'services/context.service'; import { ImageLocalStorageService } from 'services/image-local-storage.service'; import { ImagePreloaderService } from 'pages/exploration-player-page/services/image-preloader.service'; import { AppConstants } from 'app.constants'; import { SvgSanitizerService } from 'services/svg-sanitizer.service'; import { AssetsBackendApiService } from 'services/assets-backend-api.service'; import { SimpleChanges } from '@angular/core'; describe('NoninteractiveImage', () => { let component: NoninteractiveImage; let fixture: ComponentFixture<NoninteractiveImage>; let contextService: ContextService; let imageLocalStorageService: ImageLocalStorageService; let imagePreloaderService: ImagePreloaderService; let svgSanitizerService: SvgSanitizerService; let assetsBackendApiService: AssetsBackendApiService; let htmlEscaperService: HtmlEscaperService; let dataUrlSvg = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjA' + 'wMC9zdmciICB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCI+PGNpcmNsZSBjeD0iNTAiIGN5' + 'PSI1MCIgcj0iNDAiIHN0cm9rZT0iZ3JlZW4iIHN0cm9rZS13aWR0aD0iNCIgZmlsbD0ie' + 'WVsbG93IiAvPjwvc3ZnPg=='; let dataUrlPng = 'data:image/png;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjA' + 'wMC9zdmciICB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCI+PGNpcmNsZSBjeD0iNTAiIGN5' + 'PSI1MCIgcj0iNDAiIHN0cm9rZT0iZ3JlZW4iIHN0cm9rZS13aWR0aD0iNCIgZmlsbD0ie' + 'WVsbG93IiAvPjwvc3ZnPg=='; class mockHtmlEscaperService { escapedJsonToObj(data): string { return data; } } class MockSvgSanitizerService { getTrustedSvgResourceUrl(str: string): string { return str; } } let mockImageLocalStorageService = { getRawImageData: (filename) => { return dataUrlSvg; }, saveImage: (filename, imageData) => { return 'Image file save.'; }, deleteImage: (filename) => { return 'Image file is deleted.'; }, isInStorage: (filename) => { return true; } }; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [NoninteractiveImage], providers: [HtmlEscaperService, { provide: HtmlEscaperService, useClass: mockHtmlEscaperService }, { provide: ImageLocalStorageService, useValue: mockImageLocalStorageService }, { provide: SvgSanitizerService, useClass: MockSvgSanitizerService } ] }).compileComponents(); })); beforeEach(() => { htmlEscaperService = TestBed.inject(HtmlEscaperService); assetsBackendApiService = TestBed.inject(AssetsBackendApiService); svgSanitizerService = TestBed.inject(SvgSanitizerService); imageLocalStorageService = TestBed.inject(ImageLocalStorageService); imagePreloaderService = TestBed.inject(ImagePreloaderService); contextService = TestBed.inject(ContextService); fixture = TestBed.createComponent(NoninteractiveImage); component = fixture.componentInstance; component.filepathWithValue = 'img_20210704_215434_tac36akwgg_height_691_width_392.svg'; component.altWithValue = 'image label'; component.captionWithValue = 'image caption'; }); it('should initialise component when exploration loads', fakeAsync(() => { spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(true); spyOn(contextService, 'getEntityType').and.returnValue('exploration'); spyOn(imagePreloaderService, 'getImageUrlAsync').and.resolveTo(dataUrlSvg); spyOn(contextService, 'getExplorationId').and.returnValue('exp_id'); component.ngOnInit(); tick(); expect(component.filepath) .toBe('img_20210704_215434_tac36akwgg_height_691_width_392.svg'); expect(component.loadingIndicatorUrl) .toBe('/assets/images/activity/loadingIndicator.gif'); expect(component.dimensions).toEqual({ width: 392, height: 691 }); expect(component.imageContainerStyle).toEqual({ height: '691px', width: '392px' }); expect(component.isLoadingIndicatorShown).toBe(false); expect(component.isTryAgainShown).toBe(false); expect(component.imageUrl).toBe(dataUrlSvg); })); it('should fetch svg image from local storage when component is initialised', () => { spyOn(imagePreloaderService, 'inExplorationPlayer') .and.returnValue(false); spyOn(contextService, 'getImageSaveDestination').and.returnValue( AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE ); spyOn(svgSanitizerService, 'getTrustedSvgResourceUrl').and .callFake((data) => { return data; }); component.ngOnInit(); expect(component.imageUrl).toBe(dataUrlSvg); expect(component.imageCaption).toBe('image caption'); expect(component.imageAltText).toBe('image label'); }); it('should fetch png image from local storage when component is initialised', () => { spyOn(imagePreloaderService, 'inExplorationPlayer') .and.returnValue(false); spyOn(contextService, 'getImageSaveDestination').and.returnValue( AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE ); spyOn(imageLocalStorageService, 'getRawImageData').and .returnValue(dataUrlPng); component.ngOnInit(); expect(component.imageUrl).toBe(dataUrlPng); expect(component.imageCaption).toBe('image caption'); expect(component.imageAltText).toBe('image label'); }); it('should load image from server when image is not present in local storage', () => { spyOn(imagePreloaderService, 'inExplorationPlayer') .and.returnValue(false); spyOn(contextService, 'getImageSaveDestination').and.returnValue( AppConstants.IMAGE_SAVE_DESTINATION_SERVER ); spyOn(assetsBackendApiService, 'getImageUrlForPreview').and .returnValue(dataUrlPng); spyOn(contextService, 'getEntityType').and.returnValue('exploration'); spyOn(contextService, 'getEntityId').and.returnValue('expId'); component.ngOnInit(); expect(component.imageUrl).toBe(dataUrlPng); expect(component.imageCaption).toBe('image caption'); expect(component.imageAltText).toBe('image label'); }); it('should display error when the image cannot be loaded' + ' from the local storage and the server', () => { spyOn(imagePreloaderService, 'inExplorationPlayer') .and.returnValue(false); spyOn(contextService, 'getImageSaveDestination').and.returnValue( AppConstants.IMAGE_SAVE_DESTINATION_SERVER ); spyOn(contextService, 'getEntityType').and.returnValue('exploration'); spyOn(contextService, 'getEntityId').and.returnValue('expId'); spyOn(assetsBackendApiService, 'getImageUrlForPreview').and .callFake(() => { throw new Error('Error thown'); }); expect(() => { component.ngOnInit(); }).toThrowError( 'Error thown\n' + 'Entity type: exploration\n' + 'Entity ID: expId\n' + 'Filepath: img_20210704_215434_tac36akwgg_height_691_width_392.svg'); }); it('should preload image when the user click \'Reload Image\'', fakeAsync(() => { spyOn(imagePreloaderService, 'getImageUrlAsync') .and.resolveTo(dataUrlSvg); component.loadImage(); tick(); expect(component.isLoadingIndicatorShown).toBe(false); expect(component.isTryAgainShown).toBe(false); expect(component.imageUrl).toBe(dataUrlSvg); })); it('should display \'Reload Image\' when the image cannot be loaded', fakeAsync(() => { spyOn(imagePreloaderService, 'getImageUrlAsync') .and.returnValue(Promise.reject()); component.loadImage(); tick(); expect(component.isLoadingIndicatorShown).toBe(false); expect(component.isTryAgainShown).toBe(true); expect(component.imageUrl).toBe(''); })); it('should update values when user makes changes', () => { spyOn(imagePreloaderService, 'inExplorationPlayer') .and.returnValue(false); spyOn(contextService, 'getImageSaveDestination').and.returnValue( AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE ); let changes: SimpleChanges = { altWithValue: { currentValue: 'new image label', previousValue: 'image label', firstChange: false, isFirstChange: () => false } }; component.altWithValue = 'new image label'; component.ngOnChanges(changes); expect(component.imageUrl).toBe(dataUrlSvg); expect(component.imageCaption).toBe('image caption'); expect(component.imageAltText).toBe('new image label'); }); it('should not get image when filepath is not provided', () => { component.filepathWithValue = ''; component.ngOnInit(); expect(component.imageUrl).toBe(''); expect(component.imageAltText).toBe(''); expect(component.imageCaption).toBe(''); }); it('should not get image when alt text is not provided', () => { component.altWithValue = ''; component.ngOnInit(); expect(component.imageUrl).toBe(''); expect(component.imageAltText).toBe(''); expect(component.imageCaption).toBe(''); }); it('should not get image when caption text is not provided', () => { spyOn(htmlEscaperService, 'escapedJsonToObj'); component.captionWithValue = ''; component.ngOnInit(); expect(component.imageUrl).toBe(''); expect(component.imageAltText).toBe(''); expect(component.imageCaption).toBe(''); // This is tested to make sure the function did no continue to execute. expect(htmlEscaperService.escapedJsonToObj).not.toHaveBeenCalled(); }); it('should not get image when filepath is not empty', () => { spyOn(htmlEscaperService, 'escapedJsonToObj').and.returnValue(''); spyOn(imagePreloaderService, 'getDimensionsOfImage'); component.ngOnInit(); expect(component.imageUrl).toBe(''); expect(component.imageAltText).toBe(''); expect(component.imageCaption).toBe(''); // This is tested to make sure the function did no continue to execute. expect(imagePreloaderService.getDimensionsOfImage).not.toHaveBeenCalled(); }); });
the_stack
import * as $ from 'jquery'; import 'datatables'; import 'datatables.net-select'; import BootstrapNotify from "../../libs/bootstrap-notify/BootstrapNotify"; import Loader from "../../libs/loader/Loader"; import DomAttributes from "../../core/utils/DomAttributes"; import Navigation from "../../core/Navigation"; import Ajax from "../../core/ajax/Ajax"; import Initializer from "../../Initializer"; import BootboxWrapper from "../bootbox/BootboxWrapper"; import DataTransferDialogs from "../../core/ui/Dialogs/DataTransferDialogs"; import ValidationUtils from "../../core/utils/ValidationUtils"; import DomElements from "../../core/utils/DomElements"; import AjaxResponseDto from "../../DTO/AjaxResponseDto"; import AjaxEvents from "../../core/ajax/AjaxEvents"; import Ui from "../../core/ui/Ui"; export default class DataTable { /** * @type Object */ private configs = { checkboxes: { columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { style: 'multi', selector: 'td:first-child' }, order: [[ 1, 'asc' ]] } }; /** * @type Object */ private selectors = { classes:{ massActionButtonsSection : ".datatable-mass-actions", massActionRemoveFilesButton : ".datatable-remove-files", massActionTransferFilesButton : ".datatable-transfer-files", checkboxCell : ".select-checkbox" }, attributes: { targetTable : "data-target-table-selector", isFilterForTable : "data-is-filter-for-table", filterTargetTableSelector : "data-filter-target-table-selector", filterTargetColumn : "data-target-column", } }; /** * @type Object */ private api = { removeFiles: '/my-files/remove-file' }; /** * @type BootstrapNotify */ private bootstrapNotify = new BootstrapNotify(); /** * @type Ajax */ private ajax = new Ajax(); /** * @type AjaxEvents */ private ajaxEvents = new AjaxEvents(); /** * @type Initializer */ private initializer = new Initializer(); /** * @type DataTransferDialogs */ private dataTransferDialogs = new DataTransferDialogs(); /** * @description Initialize datatable based on DOM attributes */ public init() { let _this = this; $(document).ready(() => { let $allTables = $('body').find('table[data-table="true"]'); $($allTables).each(function (index, table) { let config = {}; let checkboxesAttr = $(table).attr('data-table-checkboxes'); let isSelectable = ( ValidationUtils.isTrue(checkboxesAttr) ); if( isSelectable ){ config = _this.configs.checkboxes; } // reinitializing if( !$.fn.dataTable.isDataTable(table) ) { $(table).DataTable(config); _this.attachFilterDependencyForTable(); if( isSelectable ){ _this.initSelectOptions(table); } } }); }) }; /** * @description Reinitialize existing datatable instance * * @param table_id {string} */ public reinit(table_id) { let config = {}; let table = $('#' + table_id); let checkboxesAttr = $(table).attr('data-table-checkboxes'); if( ValidationUtils.isTrue(checkboxesAttr) ){ config = this.configs.checkboxes; } $(table).DataTable(config); }; /** * Might not work * @param tableId */ public static destroyDatatableInstanceForTableId(tableId: string) { let $table = $(`#${tableId}`); $table.DataTable().destroy(); } /** * Attach all sort of events for special buttons etc. when rows in table are selectable/with checkboxes * @param table */ private initSelectOptions(table){ let massActionButtonsSection = $(this.selectors.classes.massActionButtonsSection); let $massActionButtons = $(massActionButtonsSection).find('button'); // Buttons MUST be there for this options logic if( !DomElements.doElementsExists($massActionButtons) ){ return; } this.attachSelectingCheckboxForCheckboxCell(table); this.attachEnablingAndDisablingMassActionButtonsToCheckboxCells(table, $massActionButtons); let $massActionRemoveFilesButton = $(massActionButtonsSection).find(this.selectors.classes.massActionRemoveFilesButton); let $massActionTransferFilesButton = $(massActionButtonsSection).find(this.selectors.classes.massActionTransferFilesButton); if( DomElements.doElementsExists($massActionRemoveFilesButton) ){ this.attachFilesRemoveEventOnRemoveFileButton($massActionRemoveFilesButton); } if( DomElements.doElementsExists($massActionTransferFilesButton) ){ this.attachFilesTransferEventOnTransferFileButton($massActionTransferFilesButton); } }; /** * This function is written specifically for files module * @param massActionRemoveRecordsButton */ private attachFilesRemoveEventOnRemoveFileButton(massActionRemoveRecordsButton){ let _this = this; $(massActionRemoveRecordsButton).on('click', () => { let targetTableSelector = $(massActionRemoveRecordsButton).attr(_this.selectors.attributes.targetTable); let table = $(targetTableSelector); let dataTable = $(table).DataTable(); let selectedRows = dataTable.rows( { selected: true } ); let pathsOfFilesToRemove = []; let url = _this.api.removeFiles; if( 0 === selectedRows.count() ){ return; } //@ts-ignore let filePathCellIndex = selectedRows.row(1).cell('.mass-action-remove-file-path').index().column; //@ts-ignore let fileSubdirectoryCellIndex = selectedRows.row(1).cell('.mass-action-remove-file-subdirectory').index().column; let subdirectory = ''; selectedRows.indexes().each((index) => { //@ts-ignore let rowData = selectedRows.row(index).data(); let filePath = rowData[filePathCellIndex]; pathsOfFilesToRemove.push(filePath); subdirectory = rowData[fileSubdirectoryCellIndex]; }); let data = { 'files_full_paths': pathsOfFilesToRemove, 'subdirectory' : subdirectory }; BootboxWrapper.confirm({ message: "Do You really want to remove selected files?", backdrop: true, callback: function (result) { if (result) { Loader.showMainLoader(); $.ajax({ url: url, method: "POST", data: data, }).always((data) => { Loader.hideMainLoader(); let ajaxResponseDto = AjaxResponseDto.fromArray(data); if( !ajaxResponseDto.isSuccessCode() ){ _this.bootstrapNotify.showRedNotification(ajaxResponseDto.message); return; }else { let message = ajaxResponseDto.message; if( !ajaxResponseDto.isMessageSet() ){ message = "Entity has been removed from repository"; } if( ajaxResponseDto.isTemplateSet() ){ Ui.insertIntoMainContent(ajaxResponseDto.template); _this.initializer.reinitializeLogic(); } _this.bootstrapNotify.showGreenNotification(message); } }); } } }); }); }; /** * This function is written specifically for files module * @param massActionRemoveRecordsButton */ private attachFilesTransferEventOnTransferFileButton(massActionRemoveRecordsButton){ let _this = this; $(massActionRemoveRecordsButton).on('click', () => { let targetTableSelector = $(massActionRemoveRecordsButton).attr(_this.selectors.attributes.targetTable); let table = $(targetTableSelector); let dataTable = $(table).DataTable(); let selectedRows = dataTable.rows( { selected: true } ); let pathsOfFilesToTransfer = []; if( 0 === selectedRows.count() ){ return; } //@ts-ignore let filePathCellIndex = selectedRows.row(1).cell('.mass-action-remove-file-path').index().column; selectedRows.indexes().each((index) => { //@ts-ignore let rowData = selectedRows.row(index).data(); let filePath = rowData[filePathCellIndex]; pathsOfFilesToTransfer.push(filePath); }); let callback = function (){ _this.ajaxEvents.loadModuleContentByUrl(Navigation.getCurrentUri()); BootboxWrapper.hideAll();; }; this.dataTransferDialogs.buildDataTransferDialog(pathsOfFilesToTransfer, 'My Files', callback); }); }; /** * Handle checkbox logic for clicking checkbox in checkbox cell * @param table {object} */ private attachSelectingCheckboxForCheckboxCell(table){ let allSelectCells = $(table).find(this.selectors.classes.checkboxCell); allSelectCells.on('click', (event) => { let clickedCell = event.currentTarget; let checkbox = $(clickedCell).find('input'); let isChecked = DomAttributes.isChecked(checkbox); if( isChecked ){ DomAttributes.unsetChecked(checkbox) }else{ DomAttributes.setChecked(checkbox) } }); }; /** * Handle mass action buttons disabled/enabled for selected checkboxes * @param table * @param massActionButtons */ private attachEnablingAndDisablingMassActionButtonsToCheckboxCells(table, massActionButtons){ let dataTable = $(table).DataTable(); dataTable.on('select deselect', () => { let selectedRows = dataTable.rows( { selected: true } ); let selectedRowsCount = 0; selectedRows.indexes().each((index) => { selectedRowsCount++; }); if( 0 === selectedRowsCount ){ $(massActionButtons).addClass('disabled'); return; } $(massActionButtons).removeClass('disabled'); }); }; /** * Makes the special filters above table work and filter the data in datatable */ private attachFilterDependencyForTable(){ let _this = this; let $allFiltersTable = $("[" + _this.selectors.attributes.isFilterForTable + "=true]"); let $allFiltersSelects = $allFiltersTable.find('select'); $.each( $allFiltersSelects, function( index, select ){ let $select = $(select); let targetTableSelector = $select.closest('table').attr(_this.selectors.attributes.filterTargetTableSelector); let $targetTable = $(targetTableSelector); $select.on( 'change', function () { let $selectedOption = $select.find(':selected'); let optionValue = $selectedOption.val(); let targetColumn = $select.attr(_this.selectors.attributes.filterTargetColumn); let $dataTable = $targetTable.DataTable(); // Apply the search $dataTable.columns().every(function(value, index) { // need to fix problem that table is initialized twice let column = $dataTable.column(index); let header = $dataTable.columns(0).header()[0].textContent; if ( targetColumn === header //@ts-ignore && column !== optionValue ) { //@ts-ignore column.search(optionValue) .draw(); } }); }); }); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/taskMappers"; import * as Parameters from "../models/parameters"; import { BatchServiceClientContext } from "../batchServiceClientContext"; /** Class representing a Task. */ export class Task { private readonly client: BatchServiceClientContext; /** * Create a Task. * @param {BatchServiceClientContext} client Reference to the service client. */ constructor(client: BatchServiceClientContext) { this.client = client; } /** * The maximum lifetime of a Task from addition to completion is 180 days. If a Task has not * completed within 180 days of being added it will be terminated by the Batch service and left in * whatever state it was in at that time. * @summary Adds a Task to the specified Job. * @param jobId The ID of the Job to which the Task is to be added. * @param task The Task to be added. * @param [options] The optional parameters * @returns Promise<Models.TaskAddResponse> */ add( jobId: string, task: Models.TaskAddParameter, options?: Models.TaskAddOptionalParams ): Promise<Models.TaskAddResponse>; /** * @param jobId The ID of the Job to which the Task is to be added. * @param task The Task to be added. * @param callback The callback */ add(jobId: string, task: Models.TaskAddParameter, callback: msRest.ServiceCallback<void>): void; /** * @param jobId The ID of the Job to which the Task is to be added. * @param task The Task to be added. * @param options The optional parameters * @param callback The callback */ add( jobId: string, task: Models.TaskAddParameter, options: Models.TaskAddOptionalParams, callback: msRest.ServiceCallback<void> ): void; add( jobId: string, task: Models.TaskAddParameter, options?: Models.TaskAddOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.TaskAddResponse> { return this.client.sendOperationRequest( { jobId, task, options }, addOperationSpec, callback ) as Promise<Models.TaskAddResponse>; } /** * For multi-instance Tasks, information such as affinityId, executionInfo and nodeInfo refer to * the primary Task. Use the list subtasks API to retrieve information about subtasks. * @summary Lists all of the Tasks that are associated with the specified Job. * @param jobId The ID of the Job. * @param [options] The optional parameters * @returns Promise<Models.TaskListResponse> */ list(jobId: string, options?: Models.TaskListOptionalParams): Promise<Models.TaskListResponse>; /** * @param jobId The ID of the Job. * @param callback The callback */ list(jobId: string, callback: msRest.ServiceCallback<Models.CloudTaskListResult>): void; /** * @param jobId The ID of the Job. * @param options The optional parameters * @param callback The callback */ list( jobId: string, options: Models.TaskListOptionalParams, callback: msRest.ServiceCallback<Models.CloudTaskListResult> ): void; list( jobId: string, options?: Models.TaskListOptionalParams | msRest.ServiceCallback<Models.CloudTaskListResult>, callback?: msRest.ServiceCallback<Models.CloudTaskListResult> ): Promise<Models.TaskListResponse> { return this.client.sendOperationRequest( { jobId, options }, listOperationSpec, callback ) as Promise<Models.TaskListResponse>; } /** * Note that each Task must have a unique ID. The Batch service may not return the results for each * Task in the same order the Tasks were submitted in this request. If the server times out or the * connection is closed during the request, the request may have been partially or fully processed, * or not at all. In such cases, the user should re-issue the request. Note that it is up to the * user to correctly handle failures when re-issuing a request. For example, you should use the * same Task IDs during a retry so that if the prior operation succeeded, the retry will not create * extra Tasks unexpectedly. If the response contains any Tasks which failed to add, a client can * retry the request. In a retry, it is most efficient to resubmit only Tasks that failed to add, * and to omit Tasks that were successfully added on the first attempt. The maximum lifetime of a * Task from addition to completion is 180 days. If a Task has not completed within 180 days of * being added it will be terminated by the Batch service and left in whatever state it was in at * that time. * @summary Adds a collection of Tasks to the specified Job. * @param jobId The ID of the Job to which the Task collection is to be added. * @param value The collection of Tasks to add. The maximum count of Tasks is 100. The total * serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example * if each Task has 100's of resource files or environment variables), the request will fail with * code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. * @param [options] The optional parameters * @returns Promise<Models.TaskAddCollectionResponse> */ addCollection( jobId: string, value: Models.TaskAddParameter[], options?: Models.TaskAddCollectionOptionalParams ): Promise<Models.TaskAddCollectionResponse>; /** * @param jobId The ID of the Job to which the Task collection is to be added. * @param value The collection of Tasks to add. The maximum count of Tasks is 100. The total * serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example * if each Task has 100's of resource files or environment variables), the request will fail with * code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. * @param callback The callback */ addCollection( jobId: string, value: Models.TaskAddParameter[], callback: msRest.ServiceCallback<Models.TaskAddCollectionResult> ): void; /** * @param jobId The ID of the Job to which the Task collection is to be added. * @param value The collection of Tasks to add. The maximum count of Tasks is 100. The total * serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example * if each Task has 100's of resource files or environment variables), the request will fail with * code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. * @param options The optional parameters * @param callback The callback */ addCollection( jobId: string, value: Models.TaskAddParameter[], options: Models.TaskAddCollectionOptionalParams, callback: msRest.ServiceCallback<Models.TaskAddCollectionResult> ): void; addCollection( jobId: string, value: Models.TaskAddParameter[], options?: | Models.TaskAddCollectionOptionalParams | msRest.ServiceCallback<Models.TaskAddCollectionResult>, callback?: msRest.ServiceCallback<Models.TaskAddCollectionResult> ): Promise<Models.TaskAddCollectionResponse> { return this.client.sendOperationRequest( { jobId, value, options }, addCollectionOperationSpec, callback ) as Promise<Models.TaskAddCollectionResponse>; } /** * When a Task is deleted, all of the files in its directory on the Compute Node where it ran are * also deleted (regardless of the retention time). For multi-instance Tasks, the delete Task * operation applies synchronously to the primary task; subtasks and their files are then deleted * asynchronously in the background. * @summary Deletes a Task from the specified Job. * @param jobId The ID of the Job from which to delete the Task. * @param taskId The ID of the Task to delete. * @param [options] The optional parameters * @returns Promise<Models.TaskDeleteResponse> */ deleteMethod( jobId: string, taskId: string, options?: Models.TaskDeleteMethodOptionalParams ): Promise<Models.TaskDeleteResponse>; /** * @param jobId The ID of the Job from which to delete the Task. * @param taskId The ID of the Task to delete. * @param callback The callback */ deleteMethod(jobId: string, taskId: string, callback: msRest.ServiceCallback<void>): void; /** * @param jobId The ID of the Job from which to delete the Task. * @param taskId The ID of the Task to delete. * @param options The optional parameters * @param callback The callback */ deleteMethod( jobId: string, taskId: string, options: Models.TaskDeleteMethodOptionalParams, callback: msRest.ServiceCallback<void> ): void; deleteMethod( jobId: string, taskId: string, options?: Models.TaskDeleteMethodOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.TaskDeleteResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, deleteMethodOperationSpec, callback ) as Promise<Models.TaskDeleteResponse>; } /** * For multi-instance Tasks, information such as affinityId, executionInfo and nodeInfo refer to * the primary Task. Use the list subtasks API to retrieve information about subtasks. * @summary Gets information about the specified Task. * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task to get information about. * @param [options] The optional parameters * @returns Promise<Models.TaskGetResponse> */ get( jobId: string, taskId: string, options?: Models.TaskGetOptionalParams ): Promise<Models.TaskGetResponse>; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task to get information about. * @param callback The callback */ get(jobId: string, taskId: string, callback: msRest.ServiceCallback<Models.CloudTask>): void; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task to get information about. * @param options The optional parameters * @param callback The callback */ get( jobId: string, taskId: string, options: Models.TaskGetOptionalParams, callback: msRest.ServiceCallback<Models.CloudTask> ): void; get( jobId: string, taskId: string, options?: Models.TaskGetOptionalParams | msRest.ServiceCallback<Models.CloudTask>, callback?: msRest.ServiceCallback<Models.CloudTask> ): Promise<Models.TaskGetResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, getOperationSpec, callback ) as Promise<Models.TaskGetResponse>; } /** * Updates the properties of the specified Task. * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to update. * @param [options] The optional parameters * @returns Promise<Models.TaskUpdateResponse> */ update( jobId: string, taskId: string, options?: Models.TaskUpdateOptionalParams ): Promise<Models.TaskUpdateResponse>; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to update. * @param callback The callback */ update(jobId: string, taskId: string, callback: msRest.ServiceCallback<void>): void; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to update. * @param options The optional parameters * @param callback The callback */ update( jobId: string, taskId: string, options: Models.TaskUpdateOptionalParams, callback: msRest.ServiceCallback<void> ): void; update( jobId: string, taskId: string, options?: Models.TaskUpdateOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.TaskUpdateResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, updateOperationSpec, callback ) as Promise<Models.TaskUpdateResponse>; } /** * If the Task is not a multi-instance Task then this returns an empty collection. * @summary Lists all of the subtasks that are associated with the specified multi-instance Task. * @param jobId The ID of the Job. * @param taskId The ID of the Task. * @param [options] The optional parameters * @returns Promise<Models.TaskListSubtasksResponse> */ listSubtasks( jobId: string, taskId: string, options?: Models.TaskListSubtasksOptionalParams ): Promise<Models.TaskListSubtasksResponse>; /** * @param jobId The ID of the Job. * @param taskId The ID of the Task. * @param callback The callback */ listSubtasks( jobId: string, taskId: string, callback: msRest.ServiceCallback<Models.CloudTaskListSubtasksResult> ): void; /** * @param jobId The ID of the Job. * @param taskId The ID of the Task. * @param options The optional parameters * @param callback The callback */ listSubtasks( jobId: string, taskId: string, options: Models.TaskListSubtasksOptionalParams, callback: msRest.ServiceCallback<Models.CloudTaskListSubtasksResult> ): void; listSubtasks( jobId: string, taskId: string, options?: | Models.TaskListSubtasksOptionalParams | msRest.ServiceCallback<Models.CloudTaskListSubtasksResult>, callback?: msRest.ServiceCallback<Models.CloudTaskListSubtasksResult> ): Promise<Models.TaskListSubtasksResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, listSubtasksOperationSpec, callback ) as Promise<Models.TaskListSubtasksResponse>; } /** * When the Task has been terminated, it moves to the completed state. For multi-instance Tasks, * the terminate Task operation applies synchronously to the primary task; subtasks are then * terminated asynchronously in the background. * @summary Terminates the specified Task. * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to terminate. * @param [options] The optional parameters * @returns Promise<Models.TaskTerminateResponse> */ terminate( jobId: string, taskId: string, options?: Models.TaskTerminateOptionalParams ): Promise<Models.TaskTerminateResponse>; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to terminate. * @param callback The callback */ terminate(jobId: string, taskId: string, callback: msRest.ServiceCallback<void>): void; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to terminate. * @param options The optional parameters * @param callback The callback */ terminate( jobId: string, taskId: string, options: Models.TaskTerminateOptionalParams, callback: msRest.ServiceCallback<void> ): void; terminate( jobId: string, taskId: string, options?: Models.TaskTerminateOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.TaskTerminateResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, terminateOperationSpec, callback ) as Promise<Models.TaskTerminateResponse>; } /** * Reactivation makes a Task eligible to be retried again up to its maximum retry count. The Task's * state is changed to active. As the Task is no longer in the completed state, any previous exit * code or failure information is no longer available after reactivation. Each time a Task is * reactivated, its retry count is reset to 0. Reactivation will fail for Tasks that are not * completed or that previously completed successfully (with an exit code of 0). Additionally, it * will fail if the Job has completed (or is terminating or deleting). * @summary Reactivates a Task, allowing it to run again even if its retry count has been * exhausted. * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to reactivate. * @param [options] The optional parameters * @returns Promise<Models.TaskReactivateResponse> */ reactivate( jobId: string, taskId: string, options?: Models.TaskReactivateOptionalParams ): Promise<Models.TaskReactivateResponse>; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to reactivate. * @param callback The callback */ reactivate(jobId: string, taskId: string, callback: msRest.ServiceCallback<void>): void; /** * @param jobId The ID of the Job containing the Task. * @param taskId The ID of the Task to reactivate. * @param options The optional parameters * @param callback The callback */ reactivate( jobId: string, taskId: string, options: Models.TaskReactivateOptionalParams, callback: msRest.ServiceCallback<void> ): void; reactivate( jobId: string, taskId: string, options?: Models.TaskReactivateOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.TaskReactivateResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, reactivateOperationSpec, callback ) as Promise<Models.TaskReactivateResponse>; } /** * For multi-instance Tasks, information such as affinityId, executionInfo and nodeInfo refer to * the primary Task. Use the list subtasks API to retrieve information about subtasks. * @summary Lists all of the Tasks that are associated with the specified Job. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.TaskListResponse> */ listNext( nextPageLink: string, options?: Models.TaskListNextOptionalParams ): Promise<Models.TaskListResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext( nextPageLink: string, callback: msRest.ServiceCallback<Models.CloudTaskListResult> ): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext( nextPageLink: string, options: Models.TaskListNextOptionalParams, callback: msRest.ServiceCallback<Models.CloudTaskListResult> ): void; listNext( nextPageLink: string, options?: | Models.TaskListNextOptionalParams | msRest.ServiceCallback<Models.CloudTaskListResult>, callback?: msRest.ServiceCallback<Models.CloudTaskListResult> ): Promise<Models.TaskListResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback ) as Promise<Models.TaskListResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const addOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/{jobId}/tasks", urlParameters: [Parameters.batchUrl, Parameters.jobId], queryParameters: [Parameters.apiVersion, Parameters.timeout55], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId67, Parameters.returnClientRequestId67, Parameters.ocpDate67 ], requestBody: { parameterPath: "task", mapper: { ...Mappers.TaskAddParameter, required: true } }, contentType: "application/json; odata=minimalmetadata; charset=utf-8", responses: { 201: { headersMapper: Mappers.TaskAddHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskAddHeaders } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{jobId}/tasks", urlParameters: [Parameters.batchUrl, Parameters.jobId], queryParameters: [ Parameters.apiVersion, Parameters.filter11, Parameters.select10, Parameters.expand7, Parameters.maxResults12, Parameters.timeout56 ], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId68, Parameters.returnClientRequestId68, Parameters.ocpDate68 ], responses: { 200: { bodyMapper: Mappers.CloudTaskListResult, headersMapper: Mappers.TaskListHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskListHeaders } }, serializer }; const addCollectionOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/{jobId}/addtaskcollection", urlParameters: [Parameters.batchUrl, Parameters.jobId], queryParameters: [Parameters.apiVersion, Parameters.timeout57], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId69, Parameters.returnClientRequestId69, Parameters.ocpDate69 ], requestBody: { parameterPath: { value: "value" }, mapper: { ...Mappers.TaskAddCollectionParameter, required: true } }, contentType: "application/json; odata=minimalmetadata; charset=utf-8", responses: { 200: { bodyMapper: Mappers.TaskAddCollectionResult, headersMapper: Mappers.TaskAddCollectionHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskAddCollectionHeaders } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "jobs/{jobId}/tasks/{taskId}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [Parameters.apiVersion, Parameters.timeout58], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId70, Parameters.returnClientRequestId70, Parameters.ocpDate70, Parameters.ifMatch23, Parameters.ifNoneMatch23, Parameters.ifModifiedSince27, Parameters.ifUnmodifiedSince27 ], responses: { 200: { headersMapper: Mappers.TaskDeleteHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskDeleteHeaders } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{jobId}/tasks/{taskId}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [ Parameters.apiVersion, Parameters.select11, Parameters.expand8, Parameters.timeout59 ], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId71, Parameters.returnClientRequestId71, Parameters.ocpDate71, Parameters.ifMatch24, Parameters.ifNoneMatch24, Parameters.ifModifiedSince28, Parameters.ifUnmodifiedSince28 ], responses: { 200: { bodyMapper: Mappers.CloudTask, headersMapper: Mappers.TaskGetHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskGetHeaders } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "jobs/{jobId}/tasks/{taskId}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [Parameters.apiVersion, Parameters.timeout60], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId72, Parameters.returnClientRequestId72, Parameters.ocpDate72, Parameters.ifMatch25, Parameters.ifNoneMatch25, Parameters.ifModifiedSince29, Parameters.ifUnmodifiedSince29 ], requestBody: { parameterPath: { constraints: ["options", "constraints"] }, mapper: { ...Mappers.TaskUpdateParameter, required: true } }, contentType: "application/json; odata=minimalmetadata; charset=utf-8", responses: { 200: { headersMapper: Mappers.TaskUpdateHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskUpdateHeaders } }, serializer }; const listSubtasksOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{jobId}/tasks/{taskId}/subtasksinfo", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [Parameters.apiVersion, Parameters.select12, Parameters.timeout61], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId73, Parameters.returnClientRequestId73, Parameters.ocpDate73 ], responses: { 200: { bodyMapper: Mappers.CloudTaskListSubtasksResult, headersMapper: Mappers.TaskListSubtasksHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskListSubtasksHeaders } }, serializer }; const terminateOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/{jobId}/tasks/{taskId}/terminate", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [Parameters.apiVersion, Parameters.timeout62], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId74, Parameters.returnClientRequestId74, Parameters.ocpDate74, Parameters.ifMatch26, Parameters.ifNoneMatch26, Parameters.ifModifiedSince30, Parameters.ifUnmodifiedSince30 ], responses: { 204: { headersMapper: Mappers.TaskTerminateHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskTerminateHeaders } }, serializer }; const reactivateOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "jobs/{jobId}/tasks/{taskId}/reactivate", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [Parameters.apiVersion, Parameters.timeout63], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId75, Parameters.returnClientRequestId75, Parameters.ocpDate75, Parameters.ifMatch27, Parameters.ifNoneMatch27, Parameters.ifModifiedSince31, Parameters.ifUnmodifiedSince31 ], responses: { 204: { headersMapper: Mappers.TaskReactivateHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskReactivateHeaders } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "{batchUrl}", path: "{nextLink}", urlParameters: [Parameters.nextPageLink], queryParameters: [Parameters.apiVersion], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId76, Parameters.returnClientRequestId76, Parameters.ocpDate76 ], responses: { 200: { bodyMapper: Mappers.CloudTaskListResult, headersMapper: Mappers.TaskListHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.TaskListHeaders } }, serializer };
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages Cost and Usage Report Definitions. * * > *NOTE:* The AWS Cost and Usage Report service is only available in `us-east-1` currently. * * > *NOTE:* If AWS Organizations is enabled, only the master account can use this resource. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const exampleCurReportDefinition = new aws.cur.ReportDefinition("example_cur_report_definition", { * additionalArtifacts: [ * "REDSHIFT", * "QUICKSIGHT", * ], * additionalSchemaElements: ["RESOURCES"], * compression: "GZIP", * format: "textORcsv", * reportName: "example-cur-report-definition", * s3Bucket: "example-bucket-name", * s3Region: "us-east-1", * timeUnit: "HOURLY", * }); * ``` * * ## Import * * Report Definitions can be imported using the `report_name`, e.g. * * ```sh * $ pulumi import aws:cur/reportDefinition:ReportDefinition example_cur_report_definition example-cur-report-definition * ``` */ export class ReportDefinition extends pulumi.CustomResource { /** * Get an existing ReportDefinition 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?: ReportDefinitionState, opts?: pulumi.CustomResourceOptions): ReportDefinition { return new ReportDefinition(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:cur/reportDefinition:ReportDefinition'; /** * Returns true if the given object is an instance of ReportDefinition. 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 ReportDefinition { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ReportDefinition.__pulumiType; } /** * A list of additional artifacts. Valid values are: `REDSHIFT`, `QUICKSIGHT`, `ATHENA`. When ATHENA exists within additional_artifacts, no other artifact type can be declared and reportVersioning must be `OVERWRITE_REPORT`. */ public readonly additionalArtifacts!: pulumi.Output<string[] | undefined>; /** * A list of schema elements. Valid values are: `RESOURCES`. */ public readonly additionalSchemaElements!: pulumi.Output<string[]>; /** * The Amazon Resource Name (ARN) specifying the cur report. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Compression format for report. Valid values are: `GZIP`, `ZIP`, `Parquet`. If `Parquet` is used, then format must also be `Parquet`. */ public readonly compression!: pulumi.Output<string>; /** * Format for report. Valid values are: `textORcsv`, `Parquet`. If `Parquet` is used, then Compression must also be `Parquet`. */ public readonly format!: pulumi.Output<string>; /** * Set to true to update your reports after they have been finalized if AWS detects charges related to previous months. */ public readonly refreshClosedReports!: pulumi.Output<boolean | undefined>; /** * Unique name for the report. Must start with a number/letter and is case sensitive. Limited to 256 characters. */ public readonly reportName!: pulumi.Output<string>; /** * Overwrite the previous version of each report or to deliver the report in addition to the previous versions. Valid values are: `CREATE_NEW_REPORT` and `OVERWRITE_REPORT`. */ public readonly reportVersioning!: pulumi.Output<string | undefined>; /** * Name of the existing S3 bucket to hold generated reports. */ public readonly s3Bucket!: pulumi.Output<string>; /** * Report path prefix. Limited to 256 characters. */ public readonly s3Prefix!: pulumi.Output<string | undefined>; /** * Region of the existing S3 bucket to hold generated reports. */ public readonly s3Region!: pulumi.Output<string>; /** * The frequency on which report data are measured and displayed. Valid values are: `HOURLY`, `DAILY`. */ public readonly timeUnit!: pulumi.Output<string>; /** * Create a ReportDefinition 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: ReportDefinitionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ReportDefinitionArgs | ReportDefinitionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ReportDefinitionState | undefined; inputs["additionalArtifacts"] = state ? state.additionalArtifacts : undefined; inputs["additionalSchemaElements"] = state ? state.additionalSchemaElements : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["compression"] = state ? state.compression : undefined; inputs["format"] = state ? state.format : undefined; inputs["refreshClosedReports"] = state ? state.refreshClosedReports : undefined; inputs["reportName"] = state ? state.reportName : undefined; inputs["reportVersioning"] = state ? state.reportVersioning : undefined; inputs["s3Bucket"] = state ? state.s3Bucket : undefined; inputs["s3Prefix"] = state ? state.s3Prefix : undefined; inputs["s3Region"] = state ? state.s3Region : undefined; inputs["timeUnit"] = state ? state.timeUnit : undefined; } else { const args = argsOrState as ReportDefinitionArgs | undefined; if ((!args || args.additionalSchemaElements === undefined) && !opts.urn) { throw new Error("Missing required property 'additionalSchemaElements'"); } if ((!args || args.compression === undefined) && !opts.urn) { throw new Error("Missing required property 'compression'"); } if ((!args || args.format === undefined) && !opts.urn) { throw new Error("Missing required property 'format'"); } if ((!args || args.reportName === undefined) && !opts.urn) { throw new Error("Missing required property 'reportName'"); } if ((!args || args.s3Bucket === undefined) && !opts.urn) { throw new Error("Missing required property 's3Bucket'"); } if ((!args || args.s3Region === undefined) && !opts.urn) { throw new Error("Missing required property 's3Region'"); } if ((!args || args.timeUnit === undefined) && !opts.urn) { throw new Error("Missing required property 'timeUnit'"); } inputs["additionalArtifacts"] = args ? args.additionalArtifacts : undefined; inputs["additionalSchemaElements"] = args ? args.additionalSchemaElements : undefined; inputs["compression"] = args ? args.compression : undefined; inputs["format"] = args ? args.format : undefined; inputs["refreshClosedReports"] = args ? args.refreshClosedReports : undefined; inputs["reportName"] = args ? args.reportName : undefined; inputs["reportVersioning"] = args ? args.reportVersioning : undefined; inputs["s3Bucket"] = args ? args.s3Bucket : undefined; inputs["s3Prefix"] = args ? args.s3Prefix : undefined; inputs["s3Region"] = args ? args.s3Region : undefined; inputs["timeUnit"] = args ? args.timeUnit : undefined; inputs["arn"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ReportDefinition.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ReportDefinition resources. */ export interface ReportDefinitionState { /** * A list of additional artifacts. Valid values are: `REDSHIFT`, `QUICKSIGHT`, `ATHENA`. When ATHENA exists within additional_artifacts, no other artifact type can be declared and reportVersioning must be `OVERWRITE_REPORT`. */ additionalArtifacts?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of schema elements. Valid values are: `RESOURCES`. */ additionalSchemaElements?: pulumi.Input<pulumi.Input<string>[]>; /** * The Amazon Resource Name (ARN) specifying the cur report. */ arn?: pulumi.Input<string>; /** * Compression format for report. Valid values are: `GZIP`, `ZIP`, `Parquet`. If `Parquet` is used, then format must also be `Parquet`. */ compression?: pulumi.Input<string>; /** * Format for report. Valid values are: `textORcsv`, `Parquet`. If `Parquet` is used, then Compression must also be `Parquet`. */ format?: pulumi.Input<string>; /** * Set to true to update your reports after they have been finalized if AWS detects charges related to previous months. */ refreshClosedReports?: pulumi.Input<boolean>; /** * Unique name for the report. Must start with a number/letter and is case sensitive. Limited to 256 characters. */ reportName?: pulumi.Input<string>; /** * Overwrite the previous version of each report or to deliver the report in addition to the previous versions. Valid values are: `CREATE_NEW_REPORT` and `OVERWRITE_REPORT`. */ reportVersioning?: pulumi.Input<string>; /** * Name of the existing S3 bucket to hold generated reports. */ s3Bucket?: pulumi.Input<string>; /** * Report path prefix. Limited to 256 characters. */ s3Prefix?: pulumi.Input<string>; /** * Region of the existing S3 bucket to hold generated reports. */ s3Region?: pulumi.Input<string>; /** * The frequency on which report data are measured and displayed. Valid values are: `HOURLY`, `DAILY`. */ timeUnit?: pulumi.Input<string>; } /** * The set of arguments for constructing a ReportDefinition resource. */ export interface ReportDefinitionArgs { /** * A list of additional artifacts. Valid values are: `REDSHIFT`, `QUICKSIGHT`, `ATHENA`. When ATHENA exists within additional_artifacts, no other artifact type can be declared and reportVersioning must be `OVERWRITE_REPORT`. */ additionalArtifacts?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of schema elements. Valid values are: `RESOURCES`. */ additionalSchemaElements: pulumi.Input<pulumi.Input<string>[]>; /** * Compression format for report. Valid values are: `GZIP`, `ZIP`, `Parquet`. If `Parquet` is used, then format must also be `Parquet`. */ compression: pulumi.Input<string>; /** * Format for report. Valid values are: `textORcsv`, `Parquet`. If `Parquet` is used, then Compression must also be `Parquet`. */ format: pulumi.Input<string>; /** * Set to true to update your reports after they have been finalized if AWS detects charges related to previous months. */ refreshClosedReports?: pulumi.Input<boolean>; /** * Unique name for the report. Must start with a number/letter and is case sensitive. Limited to 256 characters. */ reportName: pulumi.Input<string>; /** * Overwrite the previous version of each report or to deliver the report in addition to the previous versions. Valid values are: `CREATE_NEW_REPORT` and `OVERWRITE_REPORT`. */ reportVersioning?: pulumi.Input<string>; /** * Name of the existing S3 bucket to hold generated reports. */ s3Bucket: pulumi.Input<string>; /** * Report path prefix. Limited to 256 characters. */ s3Prefix?: pulumi.Input<string>; /** * Region of the existing S3 bucket to hold generated reports. */ s3Region: pulumi.Input<string>; /** * The frequency on which report data are measured and displayed. Valid values are: `HOURLY`, `DAILY`. */ timeUnit: pulumi.Input<string>; }
the_stack
import * as React from 'react'; import { IPropertyFieldAutoCompletePropsInternal } from './PropertyFieldAutoComplete'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import GuidHelper from './GuidHelper'; /** * @interface * PropertyFieldAutoCompleteHost properties interface * */ export interface IPropertyFieldAutoCompleteHostProps extends IPropertyFieldAutoCompletePropsInternal { } export interface IPropertyFieldAutoCompleteState { currentValue?: string; shortCurrentValue?: string; suggestions: string[]; isOpen: boolean; hover: string; keyPosition: number; isHoverDropdown: boolean; errorMessage: string; guid: string; shouldAutoComplete: boolean; scrollPosition: number; } /** * @class * Renders the controls for PropertyFieldAutoComplete component */ export default class PropertyFieldAutoCompleteHost extends React.Component<IPropertyFieldAutoCompleteHostProps, IPropertyFieldAutoCompleteState> { private async: Async; private delayedValidate: (value: string) => void; private input: TextField; /** * @function * Constructor */ constructor(props: IPropertyFieldAutoCompleteHostProps) { super(props); this.async = new Async(this); this.state = { scrollPosition: -1, shouldAutoComplete: false, keyPosition: -1, errorMessage: '', isOpen: false, isHoverDropdown: false, hover: '', guid: GuidHelper.getGuid(), currentValue: this.props.initialValue !== undefined ? this.props.initialValue : '', shortCurrentValue: this.props.initialValue !== undefined ? this.props.initialValue : '', suggestions: this.props.suggestions }; //Bind the current object to the external called onSelectDate method this.onValueChanged = this.onValueChanged.bind(this); this.onOpenDialog = this.onOpenDialog.bind(this); this.toggleHover = this.toggleHover.bind(this); this.getSuggestions = this.getSuggestions.bind(this); this.toggleHoverLeave = this.toggleHoverLeave.bind(this); this.onClickItem = this.onClickItem.bind(this); this.onInputKeyDown = this.onInputKeyDown.bind(this); this.onInputBlur = this.onInputBlur.bind(this); this.onInputKeyPress = this.onInputKeyPress.bind(this); this.onClickInput = this.onClickInput.bind(this); this.mouseEnterDropDown = this.mouseEnterDropDown.bind(this); this.mouseLeaveDropDown = this.mouseLeaveDropDown.bind(this); this.automaticScroll = this.automaticScroll.bind(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * @function * Function called when the component value changed */ private onValueChanged(newValue: string): void { //Checks if there is a method to called this.state.shortCurrentValue = newValue; this.state.currentValue = newValue; this.state.keyPosition = -1; this.state.isOpen = true; this.state.suggestions = this.getSuggestions(newValue); if (this.state.shouldAutoComplete === true) { if (this.state.suggestions !== undefined && this.state.suggestions.length > 0) { this.state.currentValue = this.state.suggestions[0]; this.state.keyPosition = 0; this.state.shouldAutoComplete = false; } } this.setState(this.state); this.delayedValidate(this.state.currentValue); } public componentDidUpdate(prevProps: IPropertyFieldAutoCompleteHostProps, prevState: IPropertyFieldAutoCompleteState, prevContext: any): void { if (this.state.currentValue != this.state.shortCurrentValue && this.state.isOpen === true) { //Set cursor position this.input.focus(); this.input.setSelectionStart(this.state.shortCurrentValue.length); this.input.setSelectionEnd(this.state.currentValue.length); if (this.state.scrollPosition !== -1) { var divDrop: any = document.getElementById("drop-" + this.state.guid); divDrop.scrollTop = this.state.scrollPosition; this.state.scrollPosition = -1; } } } private getSuggestions(value: string) { if (value == '') { return this.props.suggestions; } const escapeRegexCharacters = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp('^' + escapedValue, 'i'); return this.props.suggestions.filter(language => regex.test(language)); }; private onInputBlur(elm?: any) { if (this.state.hover == '') { this.state.isOpen = false; this.state.hover = ''; this.state.keyPosition = -1; this.setState(this.state); } } private onInputKeyPress(elm?: any) { if (elm.keyCode != 40 && elm.keyCode != 38) { this.state.keyPosition = -1; this.state.hover = ''; this.state.shouldAutoComplete = true; this.setState(this.state); } if (elm.charCode === 13) { this.state.isOpen = false; this.state.hover = ''; this.state.keyPosition = -1; this.setState(this.state); this.input.setSelectionStart(this.state.currentValue.length); this.input.setSelectionEnd(this.state.currentValue.length); } } private onInputKeyDown(elm?: any) { if (elm.keyCode === 40) { this.state.keyPosition = this.state.keyPosition + 1; if (this.state.keyPosition >= this.state.suggestions.length) this.state.keyPosition = this.state.suggestions.length - 1; this.state.currentValue = this.state.suggestions[this.state.keyPosition]; this.setState(this.state); this.automaticScroll(true); this.delayedValidate(this.state.currentValue); } else if (elm.keyCode === 38) { this.state.keyPosition = this.state.keyPosition - 1; if (this.state.keyPosition < 0) this.state.keyPosition = 0; this.state.currentValue = this.state.suggestions[this.state.keyPosition]; this.setState(this.state); this.automaticScroll(false); this.delayedValidate(this.state.currentValue); } } private automaticScroll(down: boolean): void { var lineHeight = 28; var maxHeight = 7 * lineHeight; var divDrop: any = document.getElementById("drop-" + this.state.guid); var currentScrollTop = divDrop.scrollTop; var currentTopInPixel = this.state.keyPosition * lineHeight; if (currentTopInPixel < currentScrollTop || (currentTopInPixel + lineHeight) > (currentScrollTop + maxHeight)) { //The current element is not displayed if (down === true) { if ((currentScrollTop + lineHeight) <= currentTopInPixel) this.state.scrollPosition = currentScrollTop + lineHeight; else this.state.scrollPosition = currentTopInPixel; } else { this.state.scrollPosition = currentTopInPixel; } } } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValue, value); return; } var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValue, value); this.setState({ errorMessage: result} as IPropertyFieldAutoCompleteState); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValue, value); this.setState({ errorMessage } as IPropertyFieldAutoCompleteState); }); } } else { this.notifyAfterValidate(this.props.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } /** * @function * Called when the component will unmount */ public componentWillUnmount() { if (this.async !== undefined) this.async.dispose(); } /** * @function * Function to open the dialog */ private onOpenDialog(): void { if (this.props.disabled === true) return; this.state.isOpen = !this.state.isOpen; this.setState(this.state); } /** * @function * Mouse is hover a font */ private toggleHover(element?: any) { var hoverFont: string = element.currentTarget.textContent; this.state.hover = hoverFont; this.setState(this.state); } /** * @function * Mouse is leaving a font */ private toggleHoverLeave(element?: any) { this.state.hover = ''; this.setState(this.state); } /** * @function * Mouse is hover the fontpicker */ private mouseEnterDropDown(element?: any) { this.state.isHoverDropdown = true; this.setState(this.state); } /** * @function * Mouse is leaving the fontpicker */ private mouseLeaveDropDown(element?: any) { this.state.isHoverDropdown = false; this.setState(this.state); } /** * @function * User clicked on a font */ private onClickItem(element?: any) { element.stopPropagation(); var clickedFont: string = element.currentTarget.textContent; this.state.currentValue = clickedFont; this.onOpenDialog(); this.delayedValidate(clickedFont); } private onClickInput(elm?: any) { this.state.isOpen = true; this.state.suggestions = this.getSuggestions(this.state.currentValue); this.setState(this.state); } /** * @function * Renders the controls */ public render(): JSX.Element { var fontSelect = { fontSize: '16px', width: '100%', position: 'relative', display: 'inline-block', zoom: 1 }; var dropdownColor = '1px solid #c8c8c8'; if (this.props.disabled === true) dropdownColor = '1px solid #f4f4f4'; else if (this.state.isOpen === true) dropdownColor = '1px solid #3091DE'; else if (this.state.isHoverDropdown === true) dropdownColor = '1px solid #767676'; var fontSelectA = { backgroundColor: this.props.disabled === true ? '#f4f4f4' : '#fff', borderRadius : '0px', backgroundClip : 'padding-box', border: dropdownColor, display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', position: 'relative', height: '26px', lineHeight: '26px', padding: '0 0 0 8px', color: this.props.disabled === true ? '#a6a6a6' : '#444', textDecoration: 'none', cursor: this.props.disabled === true ? 'default' : 'pointer' }; var fontSelectASpan = { marginRight: '26px', display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', lineHeight: '1.8', textOverflow: 'ellipsis', cursor: this.props.disabled === true ? 'default' : 'pointer', //fontFamily: this.state.safeSelectedFont != null && this.state.safeSelectedFont != '' ? this.state.safeSelectedFont : 'Arial', //fontSize: this.state.safeSelectedFont, fontWeight: 400 }; var fontSelectADiv = { borderRadius : '0 0px 0px 0', backgroundClip : 'padding-box', border: '0px', position: 'absolute', right: '0', top: '0', display: 'block', height: '100%', width: '22px' }; var fontSelectADivB = { display: 'block', width: '100%', height: '100%', cursor: this.props.disabled === true ? 'default' : 'pointer', marginTop: '2px' }; var fsDrop = { background: '#fff', border: '1px solid #aaa', borderTop: '0', position: 'absolute', top: '32px', left: '0', width: 'calc(100% - 2px)', //boxShadow: '0 4px 5px rgba(0,0,0,.15)', zIndex: 999, display: this.props.disabled === true ? 'none' : this.state.isOpen ? 'block' : 'none' }; var fsResults = { margin: '0 4px 4px 0', maxHeight: '190px', width: 'calc(100% - 4px)', padding: '0 0 0 4px', position: 'relative', overflowX: 'hidden', overflowY: 'auto' }; var carret: string = this.state.isOpen ? 'ms-Icon ms-Icon--ChevronUp' : 'ms-Icon ms-Icon--ChevronDown'; //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <div style={fontSelect}> <TextField disabled={this.props.disabled} ref={(input) => this.input = input } placeholder={this.props.placeHolder !== undefined ? this.props.placeHolder : ''} value={this.state.currentValue} onClick={this.onClickInput} onBlur={this.onInputBlur} onKeyUp={this.onInputKeyDown} onKeyPress={this.onInputKeyPress} onChanged={this.onValueChanged} aria-invalid={ !!this.state.errorMessage } /> <div style={fsDrop}> <ul style={fsResults} id={"drop-" + this.state.guid}> {this.state.suggestions.map((sug: string, index: number) => { var backgroundColor: string = 'transparent'; if (this.state.currentValue === sug) backgroundColor = '#c7e0f4'; else if (this.state.hover === sug) backgroundColor = '#eaeaea'; var innerStyle = { //lineHeight: '80%', height: '20px', padding: '4px 7px 4px', margin: '0', listStyle: 'none', backgroundColor: backgroundColor, cursor: 'pointer' }; return ( <li key={'autocompletepicker-' + index} role="menuitem" onMouseEnter={this.toggleHover} onClick={this.onClickItem} onMouseLeave={this.toggleHoverLeave} style={innerStyle}>{sug}</li> ); }) } </ul> </div> </div> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } }
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const userOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'user', ], }, }, options: [ { name: 'Create', value: 'create', }, { name: 'Delete', value: 'delete', }, { name: 'Get', value: 'get', }, { name: 'Get All', value: 'getAll', }, { name: 'Update', value: 'update', }, ], default: 'get', }, ]; export const userFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* user:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Short Description', name: 'short_description', type: 'string', default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, required: true, description: 'Short description of the user', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, default: {}, options: [ { displayName: 'Active', name: 'active', type: 'boolean', default: '', description: 'Whether to activate the user', }, { displayName: 'Building', name: 'building', type: 'string', default: '', description: 'The Building address', }, { displayName: 'City', name: 'city', type: 'string', default: '', description: 'City of the user', }, { displayName: 'Company', name: 'company', type: 'string', default: '', description: 'The name of the company for the user', }, { displayName: 'Country', name: 'country', type: 'string', default: '', description: 'Country of the user', }, { displayName: 'Department', name: 'department', type: 'string', default: '', description: 'Department of the user', }, { displayName: 'Email', name: 'email', type: 'string', default: '', description: 'The email address associated with the user', }, { displayName: 'First Name', name: 'first_name', type: 'string', default: '', description: 'The first name of the user', }, { displayName: 'Gender', name: 'gender', type: 'string', default: '', description: 'The gender of the user', }, { displayName: 'Home Phone', name: 'home_phone', type: 'string', default: '', description: 'Home phone of the user', }, { displayName: 'Last Name', name: 'last_name', type: 'string', default: '', description: 'The last name of the user', }, { displayName: 'Location', name: 'location', type: 'string', default: '', description: 'Location of the user', }, { displayName: 'Manager', name: 'manager', type: 'string', default: '', description: 'Manager of the user', }, { displayName: 'Middle Name', name: 'middle_name', type: 'string', default: '', description: 'The middle name of the user', }, { displayName: 'Mobile Phone', name: 'mobile_phone', type: 'string', default: '', description: 'Mobile phone number of the user', }, { displayName: 'Password', name: 'user_password', type: 'string', default: '', description: 'The user\'s password', }, { displayName: 'Password Needs Reset', name: 'password_needs_reset', type: 'boolean', default: '', description: 'Whether to require a password reset when the user logs in', }, { displayName: 'Phone', name: 'phone', type: 'string', default: '', description: 'The main phone number of the user', }, { displayName: 'Roles', name: 'roles', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getUserRoles', }, default: '', description: 'Roles of the user', }, { displayName: 'Source', name: 'source', type: 'string', default: '', description: 'The source', }, { displayName: 'State', name: 'state', type: 'string', default: '', description: 'State for the user', }, { displayName: 'Street', name: 'street', type: 'string', default: '', description: 'Street information for the user separated by comma', }, { displayName: 'Username', name: 'user_name', type: 'string', default: '', description: 'A username associated with the user (e.g. user_name.123)', }, { displayName: 'Zip Code', name: 'zip', type: 'string', default: '', description: 'Zip code for the user', }, ], }, /* -------------------------------------------------------------------------- */ /* user:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'user', ], }, }, 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: [ 'user', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 500, }, default: 50, description: 'The max number of results to return', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'user', ], operation: [ 'getAll', ], }, }, default: {}, options: [ { displayName: 'Exclude Reference Link', name: 'sysparm_exclude_reference_link', type: 'boolean', default: false, description: 'Whether to exclude Table API links for reference fields', }, { displayName: 'Fields', name: 'sysparm_fields', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getColumns', loadOptionsDependsOn: [ 'operation', ], }, default: '', description: 'A list of fields to return', }, { displayName: 'Filter', name: 'sysparm_query', type: 'string', default: '', description: 'An encoded query string used to filter the results. <a href="https://developer.servicenow.com/dev.do#!/learn/learning-plans/quebec/servicenow_application_developer/app_store_learnv2_rest_quebec_more_about_query_parameters">More info</a>', }, { displayName: 'Return Values', name: 'sysparm_display_value', type: 'options', options: [ { name: 'Actual Values', value: 'false', }, { name: 'Both', value: 'all', }, { name: 'Display Values', value: 'true', }, ], default: 'false', description: 'Choose which values to return', }, ], }, /* -------------------------------------------------------------------------- */ /* user:get/delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Retrieve Identifier', name: 'getOption', type: 'options', default: 'id', options: [ { name: 'ID', value: 'id', }, { name: 'Username', value: 'user_name', }, ], displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], }, }, required: true, description: 'Unique identifier of the user', }, { displayName: 'Username', name: 'user_name', type: 'string', default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], getOption: [ 'user_name', ], }, }, required: true, description: 'Unique identifier of the user', }, { displayName: 'User ID', name: 'id', type: 'string', default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], getOption: [ 'id', ], }, }, required: true, description: 'Unique identifier of the user', }, { displayName: 'User ID', name: 'id', type: 'string', default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'delete', ], }, }, required: true, description: 'Unique identifier of the user', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], }, }, default: {}, options: [ { displayName: 'Exclude Reference Link', name: 'sysparm_exclude_reference_link', type: 'boolean', default: false, description: 'Whether to exclude Table API links for reference fields', }, { displayName: 'Fields', name: 'sysparm_fields', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getColumns', loadOptionsDependsOn: [ 'operation', ], }, default: '', description: 'A list of fields to return', }, { displayName: 'Return Values', name: 'sysparm_display_value', type: 'options', options: [ { name: 'Actual Values', value: 'false', }, { name: 'Both', value: 'all', }, { name: 'Display Values', value: 'true', }, ], default: 'false', description: 'Choose which values to return', }, ], }, /* -------------------------------------------------------------------------- */ /* user:update */ /* -------------------------------------------------------------------------- */ { displayName: 'User ID', name: 'id', type: 'string', default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'update', ], }, }, required: true, description: 'Unique identifier of the user', }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { resource: [ 'user', ], operation: [ 'update', ], }, }, default: {}, options: [ { displayName: 'Active', name: 'active', type: 'boolean', default: '', description: 'Whether to activate the user', }, { displayName: 'Building', name: 'building', type: 'string', default: '', description: 'The Building address', }, { displayName: 'City', name: 'city', type: 'string', default: '', description: 'City of the user', }, { displayName: 'Company', name: 'company', type: 'string', default: '', description: 'The name of the company for the user', }, { displayName: 'Country', name: 'country', type: 'string', default: '', description: 'Country of the user', }, { displayName: 'Department', name: 'department', type: 'string', default: '', description: 'Department of the user', }, { displayName: 'Email', name: 'email', type: 'string', default: '', description: 'The email address associated with the user', }, { displayName: 'First Name', name: 'first_name', type: 'string', default: '', description: 'The first name of the user', }, { displayName: 'Gender', name: 'gender', type: 'string', default: '', description: 'The gender of the user', }, { displayName: 'Home Phone', name: 'home_phone', type: 'string', default: '', description: 'Home phone of the user', }, { displayName: 'Last Name', name: 'last_name', type: 'string', default: '', description: 'The last name of the user', }, { displayName: 'Location', name: 'location', type: 'string', default: '', description: 'Location of the user', }, { displayName: 'Manager', name: 'manager', type: 'string', default: '', description: 'Manager of the user', }, { displayName: 'Middle Name', name: 'middle_name', type: 'string', default: '', description: 'The middle name of the user', }, { displayName: 'Mobile Phone', name: 'mobile_phone', type: 'string', default: '', description: 'Mobile phone number of the user', }, { displayName: 'Password', name: 'user_password', type: 'string', default: '', description: 'The user\'s password', }, { displayName: 'Password Needs Reset', name: 'password_needs_reset', type: 'boolean', default: '', description: 'Whether to require a password reset when the user logs in', }, { displayName: 'Phone', name: 'phone', type: 'string', default: '', description: 'The main phone number of the user', }, { displayName: 'Roles', name: 'roles', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getUserRoles', }, default: '', description: 'Roles of the user', }, { displayName: 'Source', name: 'source', type: 'string', default: '', description: 'The source', }, { displayName: 'State', name: 'state', type: 'string', default: '', description: 'State for the user', }, { displayName: 'Street', name: 'street', type: 'string', default: '', description: 'Street information for the user separated by comma', }, { displayName: 'Username', name: 'user_name', type: 'string', default: '', description: 'A username associated with the user (e.g. user_name.123)', }, { displayName: 'Zip Code', name: 'zip', type: 'string', default: '', description: 'Zip code for the user', }, ], }, ];
the_stack
import * as React from "react"; import {ReactElement} from "react"; import {Subject, fromEvent, merge, Observer, Observable} from "rxjs"; import {delay, take} from "rxjs/operators"; import {Link} from "react-router-dom"; import {JobsonAPI} from "./JobsonAPI"; import {APIRestLink} from "./apitypes/APIRestLink"; import {APIErrorMessage} from "./apitypes/APIErrorMessage"; export class Helpers { public static promptUserToDownloadAsJSON(obj: any): void { const objJSON = JSON.stringify(obj, null, 2); const blob = new Blob([objJSON], {type: "application/json"}); Helpers.promptUserToDownload(blob, "query.json"); } public static promptUserToDownload(blob: Blob, fileName: string): void { // If it's shitty IE if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { const blobUrl = URL.createObjectURL(blob); const downloadLink = document.createElement("a"); downloadLink.href = blobUrl; downloadLink.download = fileName; downloadLink.style.visibility = "hidden"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } public static extractParams(search: string): { [k: string]: any } { if (!search) return {}; let pairs = search.substring(1).split("&"), obj: { [k: string]: string } = {}, pair, i; for (i in pairs) { if (pairs[i] === "") continue; pair = pairs[i].split("="); obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return obj; } public static promptUserForFiles(mimeTypes: string = "", allowMultipleFiles: boolean = true): Promise<FileList> { return new Promise((resolve, reject) => { const fileInputEl = document.createElement("input"); if (allowMultipleFiles) fileInputEl.multiple = true; fileInputEl.style.visibility = "hidden"; fileInputEl.type = "file"; fileInputEl.accept = mimeTypes; const changeEvents = fromEvent(fileInputEl, "change"); const focusEvents = fromEvent(document, "focus").pipe(delay(50)); merge(changeEvents, focusEvents) .pipe(take(1)) .subscribe(() => { if (fileInputEl.files !== null && fileInputEl.files.length === 1) resolve(fileInputEl.files); else reject("User did not select a file"); }); document.body.appendChild(fileInputEl); fileInputEl.click(); document.body.removeChild(fileInputEl); }); } public static createObservableSocket(wsURL: string): Observable<any> { const subject = new Subject(); Helpers._observeWebsocket(wsURL, subject); return subject; } private static _observeWebsocket(wsURL: string, observer: Observer<any>): void { const ws = new WebSocket(wsURL); ws.onmessage = (e) => observer.next(e); ws.onerror = (e) => observer.error(e); ws.onclose = (e) => { if (Helpers._websocketClosedDueToTimeout(e)) { this._observeWebsocket(wsURL, observer); } else { observer.complete(); } }; } private static _websocketClosedDueToTimeout(wsCloseEvent: CloseEvent): boolean { const WEBSOCKET_IDLE_TIMEOUT_CODE = 1001; return wsCloseEvent.code === WEBSOCKET_IDLE_TIMEOUT_CODE; } public static promptUserForFile(mimeTypes = ""): Promise<File> { return Helpers.promptUserForFiles(mimeTypes, false).then(files => files[0]); } public static readFileAsText(file: Blob): Promise<string> { return new Promise((resolve, reject) => { const textReader = new FileReader(); textReader.onload = () => resolve(textReader.result as string); textReader.onerror = () => reject(textReader.error); textReader.readAsText(file); }); } static dissasoc(o: any, k: string): any { const copy = Object.assign({}, o); delete copy[k]; return copy; } static fetchBlobContentsAsText(blob: Blob): Promise<string> { return new Promise((resolve) => { const reader = new FileReader(); reader.onload = () => { resolve(reader.result as string); }; reader.readAsText(blob); }); } static reject<T>(ary: T[], el: T): T[] { const i = ary.indexOf(el); return ary.filter((e, j) => j !== i); } static makeWebsocketPath(p: string): string { const scheme = window.location.protocol.startsWith("https") ? "wss" : "ws"; const prefix = `${scheme}://${window.location.host}`; if (p.startsWith("/")) { return prefix + p; } else if (window.location.pathname.endsWith("/")) { return prefix + window.location.pathname + p; } else { return prefix + window.location.pathname + "/" + p; } } static isEmpty(o: any): boolean { return Object.keys(o).length === 0; } static deepEquals(o1: any, o2: any): boolean { return o1 === o2; // TODO: Recursive impl. } static forEachKv<V>(f: (k: string, v: V) => void, o: { [key: string]: V }): void { Object.keys(o).forEach(k => f(k, o[k])); } static mapKv<V1, V2>(f: (k: string, v: V1) => V2, o: { [key: string]: V1 }): { [key: string]: V2 } { const ret: { [k: string]: V2 } = {}; Object.keys(o).forEach(k => ret[k] = f(k, o[k])); return ret; } public static mapKvToArray<V1, V2>(f: (k: string, v: V1) => V2, o: { [key: string]: V1 }): V2[] { return Object.keys(o).map(k => f(k, o[k])); } static isTerminalStatus(status: string): boolean { switch (status) { case "aborted": case "fatal-error": case "finished": return true; default: return false; } } static renderStatusField(status: string): ReactElement<any> { switch (status) { case "aborted": return <div className="ui orange horizontal basic label">{status}</div>; case "fatal-error": return <div className="ui red horizontal basic label">{status}</div>; case "finished": return <div className="ui green horizontal basic label">{status}</div>; case "running": return ( <div className="ui horizontal basic label"> <div className="ui tiny active inline loader"/> Running </div> ); default: return <div className="ui horizontal basic label">{status}</div>; } } static renderDownloadButton(href: string): ReactElement<any> { return ( <a className="ui right floated primary button" href={href}> <i className="download icon"/> Download </a> ); } static jobStatusColor(jobStatus: string): string { switch (jobStatus) { case "submitted": return "grey"; case "fatal-error": return "red"; case "finished": return "green"; case "running": return "grey"; case "aborted": return "orange"; default: return "grey"; } } static renderLoadingMessage(noun: string): ReactElement<any> { return ( <div className="ui icon message"> <i className="notched circle loading icon"/> <div className="content"> <div className="header"> Loading </div> <p> Fetching {noun} from the Jobson API. </p> </div> </div> ); } static renderAPIErrorMessage(noun: string, apiError: APIErrorMessage, retryCallback: (() => void)): ReactElement<any> { const header = <span>Error loading {noun}</span>; const body = <div> <p> There was an error loading {noun} from the Jobson API. The APIs error message was: {apiError.message}. </p> <button className="ui primary icon button" onClick={retryCallback}> <i className="refresh icon"/> Try Again </button> </div>; return Helpers.renderErrorMessage(header, body); } static renderErrorMessage(header: ReactElement<any> | string, content: ReactElement<any> | string): ReactElement<any> { return ( <div className="ui negative icon message"> <i className="warning circle icon"/> <div className="content"> <div className="header"> {header} </div> {content} </div> </div> ); } static renderWarningMessage(header: ReactElement<any> | string, content: ReactElement<any> | string): ReactElement<any> { return ( <div className="ui yellow icon message"> <i className="warning circle icon"/> <div className="content"> <div className="header"> {header} </div> {content} </div> </div> ); } static renderAllJobActions(jobsonApi: JobsonAPI, routeProps: any, jobId: string, restLinks: { [name: string]: APIRestLink }): ReactElement<any>[] { const btnsWithoutView = Helpers.renderJobActionsWithoutViewBtn(jobsonApi, routeProps, jobId, restLinks); const selfLinkIdx = Object.keys(restLinks).indexOf("self"); if (selfLinkIdx !== -1) { const viewBtn = ( <Link to={"/jobs/" + jobId} className="ui tiny compact button" key={selfLinkIdx}> View </Link> ); return btnsWithoutView.concat([viewBtn]); } else { return btnsWithoutView; } } static renderJobActionsWithoutViewBtn(jobsonApi: JobsonAPI, routeProps: any, jobId: string, restLinks: { [name: string]: APIRestLink }): any[] { const restLinkActions: (ReactElement<any> | null)[] = Object.keys(restLinks) .map((linkName, i) => { switch (linkName) { case "abort": const href = restLinks[linkName].href; return ( <button className="ui tiny compact negative button" key={i} onClick={() => jobsonApi.postEmptyRequestToRESTHref(href)}> Abort </button> ); default: return null; } }) .filter(el => el !== null); const copyLink = <Link to={"/submit?based-on=" + jobId} className="ui tiny compact button" key={Object.keys(restLinks).length}> Copy </Link>; return restLinkActions.concat([copyLink]); } static toB64(file: File): Promise<string> { const dataPrefixRegex = /^data:[^\/]*\/[^;]*;base64,/; return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = e => { // e.g. // data:application/octet-stream;base64,<some_b64_str>* const b64WithDataPrefix = e.target.result as string; // Remove the URL prefix that the `FileReader` adds const b64str = b64WithDataPrefix.replace(dataPrefixRegex, ""); resolve(b64str); }; reader.onerror = e => { reject(e); }; reader.onabort = e => { reject(e); }; reader.readAsDataURL(file); }); } }
the_stack
import {BookmarksPageState, changeFolderOpen, clearSearch, createBookmark, createEmptyState, deselectItems, editBookmark, FolderOpenState, getDisplayedList, isShowingSearch, moveBookmark, NodeMap, reduceAction, removeBookmark, reorderChildren, selectFolder, SelectFolderAction, SelectionState, SelectItemsAction, setSearchResults, setSearchTerm, updateAnchor, updateFolderOpenState, updateNodes, updateSelectedFolder, updateSelection} from 'chrome://bookmarks/bookmarks.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {createFolder, createItem, normalizeIterable, testTree} from './test_util.js'; suite('selection state', function() { let selection: SelectionState; let action; function select( items: string[], anchor: string, clear: boolean, toggle: boolean): SelectItemsAction { return { name: 'select-items', clear: clear, anchor: anchor, items: items, toggle: toggle, }; } setup(function() { selection = { anchor: null, items: new Set(), }; }); test('can select an item', function() { action = select(['1'], '1', true, false); selection = updateSelection(selection, action); assertDeepEquals(['1'], normalizeIterable(selection.items)); assertEquals('1', selection.anchor); // Replace current selection. action = select(['2'], '2', true, false); selection = updateSelection(selection, action); assertDeepEquals(['2'], normalizeIterable(selection.items)); assertEquals('2', selection.anchor); // Add to current selection. action = select(['3'], '3', false, false); selection = updateSelection(selection, action); assertDeepEquals(['2', '3'], normalizeIterable(selection.items)); assertEquals('3', selection.anchor); }); test('can select multiple items', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); assertDeepEquals(['1', '2', '3'], normalizeIterable(selection.items)); action = select(['3', '4'], '4', false, false); selection = updateSelection(selection, action); assertDeepEquals(['1', '2', '3', '4'], normalizeIterable(selection.items)); }); test('is cleared when selected folder changes', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); action = selectFolder('2'); selection = updateSelection(selection, action!); assertDeepEquals(new Set(), selection.items); }); test('is cleared when search finished', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); action = setSearchResults(['2']); selection = updateSelection(selection, action); assertDeepEquals(new Set(), selection.items); }); test('is cleared when search cleared', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); action = clearSearch(); selection = updateSelection(selection, action); assertDeepEquals(new Set(), selection.items); }); test('deselect items', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); action = deselectItems(); selection = updateSelection(selection, action); assertDeepEquals(new Set(), selection.items); }); test('toggle an item', function() { action = select(['1', '2', '3'], '3', true, false); selection = updateSelection(selection, action); action = select(['1'], '3', false, true); selection = updateSelection(selection, action); assertDeepEquals(['2', '3'], normalizeIterable(selection.items)); }); test('update anchor', function() { action = updateAnchor('3'); selection = updateSelection(selection, action); assertEquals('3', selection.anchor); }); test('deselects items when they are deleted', function() { const nodeMap = testTree( createFolder( '1', [ createItem('2'), createItem('3'), createItem('4'), ]), createItem('5')); action = select(['2', '4', '5'], '4', true, false); selection = updateSelection(selection, action); action = removeBookmark('1', '0', 0, nodeMap); selection = updateSelection(selection, action); assertDeepEquals(['5'], normalizeIterable(selection.items)); assertEquals(null, selection.anchor); }); test('deselects items when they are moved to a different folder', function() { action = select(['2', '3'], '2', true, false); selection = updateSelection(selection, action); // Move item '2' from the 1st item in '0' to the 0th item in '1'. action = moveBookmark('2', '1', 0, '0', 1); selection = updateSelection(selection, action); assertDeepEquals(['3'], normalizeIterable(selection.items)); assertEquals(null, selection.anchor); }); }); suite('folder open state', function() { let nodes: NodeMap; let folderOpenState: FolderOpenState; let action; setup(function() { nodes = testTree( createFolder( '1', [ createFolder('2', []), createItem('3'), ]), createFolder('4', [])); folderOpenState = new Map(); }); test('close folder', function() { action = changeFolderOpen('2', false); folderOpenState = updateFolderOpenState(folderOpenState, action, nodes); assertFalse(folderOpenState.has('1')); assertFalse(folderOpenState.get('2')!); }); test('select folder with closed parent', function() { // Close '1' action = changeFolderOpen('1', false); folderOpenState = updateFolderOpenState(folderOpenState, action, nodes); assertFalse(folderOpenState.get('1')!); assertFalse(folderOpenState.has('2')); // Should re-open when '2' is selected. action = selectFolder('2'); folderOpenState = updateFolderOpenState(folderOpenState, action!, nodes); assertTrue(folderOpenState.get('1')!); assertFalse(folderOpenState.has('2')); // The parent should be set to permanently open, even if it wasn't // explicitly closed. folderOpenState = new Map(); action = selectFolder('2'); folderOpenState = updateFolderOpenState(folderOpenState, action!, nodes); assertTrue(folderOpenState.get('1')!); assertFalse(folderOpenState.has('2')); }); test('move nodes in a closed folder', function() { // Moving bookmark items should not open folders. folderOpenState = new Map([['1', false]]); action = moveBookmark('3', '1', 1, '1', 0); folderOpenState = updateFolderOpenState(folderOpenState, action, nodes); assertFalse(folderOpenState.get('1')!); // Moving folders should open their parents. folderOpenState = new Map([['1', false], ['2', false]]); action = moveBookmark('4', '2', 0, '0', 1); folderOpenState = updateFolderOpenState(folderOpenState, action, nodes); assertTrue(folderOpenState.get('1')!); assertTrue(folderOpenState.get('2')!); }); }); suite('selected folder', function() { let nodes: NodeMap; let selectedFolder: string; let action: SelectFolderAction; setup(function() { nodes = testTree(createFolder('1', [ createFolder( '2', [ createFolder('3', []), createFolder('4', []), ]), ])); selectedFolder = '1'; }); test('updates from selectFolder action', function() { action = selectFolder('2')!; selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); assertEquals('2', selectedFolder); }); test('updates when parent of selected folder is closed', function() { action = selectFolder('2')!; selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); action = changeFolderOpen('1', false); selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); assertEquals('1', selectedFolder); }); test('selects ancestor when selected folder is deleted', function() { action = selectFolder('3')!; selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); // Delete the selected folder: action = removeBookmark('3', '2', 0, nodes); selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); assertEquals('2', selectedFolder); action = selectFolder('4')!; selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); // Delete an ancestor of the selected folder: action = removeBookmark('2', '1', 0, nodes); selectedFolder = updateSelectedFolder(selectedFolder, action, nodes); assertEquals('1', selectedFolder); }); }); suite('node state', function() { let nodes: NodeMap; let action; setup(function() { nodes = testTree( createFolder( '1', [ createItem('2', {title: 'a', url: 'a.com'}), createItem('3'), createFolder('4', []), ]), createFolder('5', [])); }); test('updates when a node is edited', function() { action = editBookmark('2', {title: 'b'}); nodes = updateNodes(nodes, action); assertEquals('b', nodes['2']!.title); assertEquals('a.com', nodes['2']!.url); action = editBookmark('2', {title: 'c', url: 'c.com'}); nodes = updateNodes(nodes, action); assertEquals('c', nodes['2']!.title); assertEquals('c.com', nodes['2']!.url); action = editBookmark('4', {title: 'folder'}); nodes = updateNodes(nodes, action); assertEquals('folder', nodes['4']!.title); assertEquals(undefined, nodes['4']!.url); // Cannot edit URL of a folder: action = editBookmark('4', {title: 'folder', url: 'folder.com'}); nodes = updateNodes(nodes, action); assertEquals('folder', nodes['4']!.title); assertEquals(undefined, nodes['4']!.url); }); test('updates when a node is created', function() { // Create a folder. const folder = { title: '', id: '6', parentId: '1', index: 2, }; action = createBookmark(folder.id, folder); nodes = updateNodes(nodes, action); assertEquals('1', nodes['6']!.parentId); assertDeepEquals([], nodes['6']!.children); assertDeepEquals(['2', '3', '6', '4'], nodes['1']!.children); // Add a new item to that folder. const item = { title: '', id: '7', parentId: '6', index: 0, url: 'https://www.example.com', }; action = createBookmark(item.id, item); nodes = updateNodes(nodes, action); assertEquals('6', nodes['7']!.parentId); assertEquals(undefined, nodes['7']!.children); assertDeepEquals(['7'], nodes['6']!.children); }); test('updates when a node is deleted', function() { action = removeBookmark('3', '1', 1, nodes); nodes = updateNodes(nodes, action); assertDeepEquals(['2', '4'], nodes['1']!.children); assertDeepEquals(['2', '4'], nodes['1']!.children); assertEquals(undefined, nodes['3']); }); test('removes all children of deleted nodes', function() { action = removeBookmark('1', '0', 0, nodes); nodes = updateNodes(nodes, action); assertDeepEquals(['0', '5'], Object.keys(nodes).sort()); }); test('updates when a node is moved', function() { // Move within the same folder backwards. action = moveBookmark('3', '1', 0, '1', 1); nodes = updateNodes(nodes, action); assertDeepEquals(['3', '2', '4'], nodes['1']!.children); // Move within the same folder forwards. action = moveBookmark('3', '1', 2, '1', 0); nodes = updateNodes(nodes, action); assertDeepEquals(['2', '4', '3'], nodes['1']!.children); // Move between different folders. action = moveBookmark('4', '5', 0, '1', 1); nodes = updateNodes(nodes, action); assertDeepEquals(['2', '3'], nodes['1']!.children); assertDeepEquals(['4'], nodes['5']!.children); }); test('updates when children of a node are reordered', function() { action = reorderChildren('1', ['4', '2', '3']); nodes = updateNodes(nodes, action); assertDeepEquals(['4', '2', '3'], nodes['1']!.children); }); }); suite('search state', function() { let state: BookmarksPageState; setup(function() { // Search touches a few different things, so we test using the entire state. state = createEmptyState(); state.nodes = testTree(createFolder('1', [ createFolder( '2', [ createItem('3'), ]), ])); }); test('updates when search is started and finished', function() { let action; action = selectFolder('2'); state = reduceAction(state, action!); action = setSearchTerm('test'); state = reduceAction(state, action!); assertEquals('test', state.search.term); assertTrue(state.search.inProgress); // UI should not have changed yet. assertFalse(isShowingSearch(state)); assertDeepEquals(['3'], getDisplayedList(state)); action = setSearchResults(['2', '3']); const searchedState = reduceAction(state, action); assertFalse(searchedState.search.inProgress); // UI changes once search results arrive. assertTrue(isShowingSearch(searchedState)); assertDeepEquals(['2', '3'], getDisplayedList(searchedState)); // Case 1: Clear search by setting an empty search term. action = setSearchTerm(''); const clearedState = reduceAction(searchedState, action); // Should go back to displaying the contents of '2', which was shown before // the search. assertEquals('2', clearedState.selectedFolder); assertFalse(isShowingSearch(clearedState)); assertDeepEquals(['3'], getDisplayedList(clearedState)); assertEquals('', clearedState.search.term); assertDeepEquals(null, clearedState.search.results); // Case 2: Clear search by selecting a new folder. action = selectFolder('1'); const selectedState = reduceAction(searchedState, action!); assertEquals('1', selectedState.selectedFolder); assertFalse(isShowingSearch(selectedState)); assertDeepEquals(['2'], getDisplayedList(selectedState)); assertEquals('', selectedState.search.term); assertDeepEquals(null, selectedState.search.results); }); test('results do not clear while performing a second search', function() { let action = setSearchTerm('te'); state = reduceAction(state, action); assertFalse(isShowingSearch(state)); action = setSearchResults(['2', '3']); state = reduceAction(state, action); assertFalse(state.search.inProgress); assertTrue(isShowingSearch(state)); // Continuing the search should not clear the previous results, which should // continue to show until the new results arrive. action = setSearchTerm('test'); state = reduceAction(state, action); assertTrue(state.search.inProgress); assertTrue(isShowingSearch(state)); assertDeepEquals(['2', '3'], getDisplayedList(state)); action = setSearchResults(['3']); state = reduceAction(state, action); assertFalse(state.search.inProgress); assertTrue(isShowingSearch(state)); assertDeepEquals(['3'], getDisplayedList(state)); }); test('removes deleted nodes', function() { let action; action = setSearchTerm('test'); state = reduceAction(state, action); action = setSearchResults(['1', '3', '2']); state = reduceAction(state, action); action = removeBookmark('2', '1', 0, state.nodes); state = reduceAction(state, action); // 2 and 3 should be removed, since 2 was deleted and 3 was a descendant of // 2. assertDeepEquals(['1'], state.search.results); }); });
the_stack
import React, { useContext, useState } from "react" import { createStyles, Theme, makeStyles } from "@material-ui/core/styles" import firebase from "firebase" import { loadStripe } from "@stripe/stripe-js" import { CardElement, Elements, useStripe, useElements, } from "@stripe/react-stripe-js" import "firebase/functions" import ArrowBackIcon from "@material-ui/icons/ArrowBack"; import { Paper, AppBar, Toolbar, Button, Typography, Tooltip, IconButton, FormControlLabel, Checkbox, Card } from "@material-ui/core" import { List, ListItem, ListItemText, ListItemIcon } from "@material-ui/core"; import AddIcon from "@material-ui/icons/Add"; import Loading from "components/Loading" import { Container, ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails, ExpansionPanelActions, Divider, Box } from "@material-ui/core"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import CardBrand from "common/stripe/CardBrand" import * as Commerce from "models/commerce" import { PaymentMethod } from "@stripe/stripe-js" import DataLoading from "components/DataLoading"; import { useDialog } from "components/Dialog" import { useFetchList } from "hooks/stripe" import { useAuthUser } from "hooks/auth" import { UserContext } from "hooks/commerce" import { useProcessing } from "components/Processing"; import { usePush, usePop } from "components/Navigation"; import { useSnackbar } from "components/Snackbar" export default ({ user }: { user: Commerce.User }) => { const [setProcessing] = useProcessing() const [paymentMethods, isLoading, error, setPaymentMethods] = useFetchList<PaymentMethod>("stripe-v1-paymentMethod-list", { type: "card" }) const [setMessage] = useSnackbar() const [showDialog, close] = useDialog() const [push] = usePush() const pop = usePop() if (error) { console.error(error) } const setDefaultPaymentMethod = async (paymentMethod: PaymentMethod) => { setProcessing(true) const customerUpdate = firebase.functions().httpsCallable("stripe-v1-customer-update") try { const response = await customerUpdate({ // payment_method: paymentMethod.id, invoice_settings: { default_payment_method: paymentMethod.id } }) const { result, error } = response.data if (error) { console.error(error) setProcessing(false) setMessage("error", error.message) return } const card = new Commerce.Card(paymentMethod.id) card.brand = paymentMethod.card!.brand card.expMonth = paymentMethod.card!.exp_month card.expYear = paymentMethod.card!.exp_year card.last4 = paymentMethod.card!.last4 await user.documentReference.set({ defaultCard: card.convert() }, { merge: true }) console.log("[APP] set default payment method", result) } catch (error) { console.error(error) } setProcessing(false) pop() } const paymentMethodDetach = async (deletePaymentMethod: PaymentMethod) => { if (!deletePaymentMethod) { return } setProcessing(true) try { const detach = firebase.functions().httpsCallable("stripe-v1-paymentMethod-detach") const response = await detach({ paymentMethodID: deletePaymentMethod.id }) const { result, error } = response.data if (error) { console.error(error) setProcessing(false) setMessage("error", error.message) return } console.log("[APP] detach payment method", result) const data = paymentMethods.filter(method => method.id !== deletePaymentMethod.id) if (deletePaymentMethod.id === user.defaultCard?.id) { if (data.length > 0) { const method = data[0] await setDefaultPaymentMethod(method) } else { await user.documentReference.set({ defaultCard: null }, { merge: true }) } } setPaymentMethods(data) } catch (error) { console.error(error) } setProcessing(false) } return ( <Paper> <AppBar position="static" color="transparent" elevation={0}> <Toolbar> <Tooltip title="Back" onClick={() => { pop() }}> <IconButton> <ArrowBackIcon color="inherit" /> </IconButton> </Tooltip> <Box fontSize={18} fontWeight={600}> Card </Box> </Toolbar> </AppBar> <List> <ListItem button onClick={() => { push(<CardInput callback={(paymentMethod) => { setPaymentMethods([...paymentMethods, paymentMethod]) }} />) }}> <ListItemIcon> <AddIcon color="secondary" /> </ListItemIcon> <ListItemText primary={`Add new payment method`} /> </ListItem> </List> {isLoading ? <DataLoading /> : paymentMethods.map(method => { return ( <ExpansionPanel key={method.id} > <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <FormControlLabel onClick={async (event) => { event.stopPropagation() await setDefaultPaymentMethod(method) }} onFocus={(event) => event.stopPropagation()} control={<Checkbox checked={user.defaultCard?.id === method.id} />} label={ <Box display="flex" alignItems="center" flexGrow={1} style={{ width: "140px" }}> <Box display="flex" alignItems="center" flexGrow={1}> <i className={`pf ${CardBrand[method.card!.brand]}`}></i> </Box> <Box justifySelf="flex-end"> {`• • • • ${method.card?.last4}`} </Box> </Box> } /> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> expire {`${method.card?.exp_year}/${method.card?.exp_month}`} </Typography> </ExpansionPanelDetails> <Divider /> <ExpansionPanelActions> <Button size="small" onClick={async () => { showDialog("Delete", "Do you want to remove it?", [ { title: "Cancel", handler: close }, { title: "OK", handler: async () => { await paymentMethodDetach(method) } }]) }}>Delete</Button> </ExpansionPanelActions> </ExpansionPanel> ) }) } </Paper> ) } const STRIPE_API_KEY = process.env.STRIPE_API_KEY! const stripePromise = loadStripe(STRIPE_API_KEY) const CARD_OPTIONS = { style: { base: { fontSize: "16px", }, invalid: { iconColor: "#FFC7EE", color: "#FFC7EE", }, }, hidePostalCode: true }; const CardInput = ({ callback }: { callback?: (paymentMethod: PaymentMethod) => void }) => { return ( <Elements stripe={stripePromise}> <Form callback={callback} /> </Elements> ) } const useStyles = makeStyles((theme: Theme) => createStyles({ box: { padding: theme.spacing(3), }, button: { width: "100%", flexGrow: 1, marginTop: theme.spacing(4) } }), ); const Form = ({ callback }: { callback?: (paymentMethod: PaymentMethod) => void }) => { const classes = useStyles() const [auth] = useAuthUser() const [user, isUserLoading] = useContext(UserContext) const stripe = useStripe(); const elements = useElements() const [isDisabled, setDisable] = useState(true) const [setProcessing] = useProcessing() const pop = usePop() const handleSubmit = async (event) => { event.preventDefault() if (!auth) return if (!stripe) return if (!elements) return const card = elements.getElement(CardElement) if (!card) return setProcessing(true) try { const { error, paymentMethod } = await stripe.createPaymentMethod({ type: "card", card: card }) if (error) { console.log(error) setProcessing(false) return } if (!paymentMethod) { setProcessing(false) return } const cardMethod = new Commerce.Card(paymentMethod.id) cardMethod.id = paymentMethod.id cardMethod.brand = paymentMethod.card!.brand cardMethod.expMonth = paymentMethod.card!.exp_month cardMethod.expYear = paymentMethod.card!.exp_year cardMethod.last4 = paymentMethod.card!.last4 let updateData: any = { defaultCard: cardMethod.convert() } try { const attach = firebase.functions().httpsCallable("stripe-v1-paymentMethod-attach") const response = await attach({ paymentMethodID: paymentMethod.id }) const { error, result } = response.data if (error) { console.error(error) setProcessing(false) return } if (result) { if (callback) { callback(result) } } console.log("[APP] attach payment method", result) } catch (error) { throw error } // else { // const create = firebase.functions().httpsCallable("stripe-v1-customer-create") // const response = await create({ // payment_method: paymentMethod.id, // phone: auth.phoneNumber, // invoice_settings: { // default_payment_method: paymentMethod.id // }, // metadata: { // uid: auth.uid // } // }) // const { error, customer } = response.data // if (error) { // console.error(error) // setProcessing(false) // return // } // console.log("[APP] create customer", customer) // if (customer) { // updateData["stripe"] = { // customerID: customer.id, // link: `https://dashboard.stripe.com${ // customer.livemode ? "" : "/test" // }/customers/${customer.id}` // } // } // } await new Commerce.User(auth.uid).documentReference.set(updateData, { merge: true }) setProcessing(false) pop() } catch (error) { setProcessing(false) console.log(error) } }; if (isUserLoading) { return <Loading /> } else { return ( <Paper> <AppBar position="static" color="transparent" elevation={0}> <Toolbar disableGutters> <Tooltip title="Back" onClick={() => { pop() }}> <IconButton> <ArrowBackIcon color="inherit" /> </IconButton> </Tooltip> <Box fontSize={18} fontWeight={600}> Card </Box> </Toolbar> </AppBar> <Box p={2}> <form> <CardElement options={CARD_OPTIONS} onChange={(e) => { setDisable(!e.complete) }} /> <Button className={classes.button} variant="contained" color="primary" size="large" disabled={isDisabled} onClick={handleSubmit}>Continue to Payment</Button> </form> </Box> </Paper> ) } }
the_stack
import debug from 'debug'; import { assert } from 'chai'; import TelegramBot from 'node-telegram-bot-api'; import type { InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup } from 'typegram'; import { getServerAndClient, assertEventuallyTrue, delay } from './utils'; import { TelegramBotEx, attachMessageHandler, DeleterBot, CallbackQBot, Logger, } from './testBots'; import type { StoredBotUpdate } from '../telegramServer'; const debugTest = debug('TelegramServer:test'); function isReplyKeyboard(markup: object | undefined): markup is ReplyKeyboardMarkup { return markup !== undefined && 'keyboard' in markup; } function isInlineKeyboard(markup: object | undefined): markup is InlineKeyboardMarkup { return markup !== undefined && 'inline_keyboard' in markup; } function isCommonButton(btn: unknown): btn is KeyboardButton.CommonButton { return typeof btn === 'object' && btn !== null && 'text' in btn; } function isBotUpdate(upd: object | undefined): upd is StoredBotUpdate { return upd !== undefined && 'message' in upd; } describe('Telegram Server', () => { const token = 'sampleToken'; it('should receive user`s messages', async () => { const { server, client } = await getServerAndClient(token); const message = client.makeMessage('/start'); const res = await client.sendMessage(message); await server.stop(); assert.equal(true, res.ok); }); it('should provide user messages to bot', async () => { const { server, client } = await getServerAndClient(token); const message = client.makeMessage('/start'); const res = await client.sendMessage(message); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new TelegramBotEx(token, botOptions); const res2 = await telegramBot.waitForReceiveUpdate(); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await server.stop(); assert.equal('/start', res2.text); }); it('should receive bot`s messages', async () => { const { server, client } = await getServerAndClient(token); const message = client.makeMessage('/start'); const botWaiter = server.waitBotMessage(); const res = await client.sendMessage(message); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new TelegramBotEx(token, botOptions); attachMessageHandler(telegramBot); const res2 = await telegramBot.waitForReceiveUpdate(); assert.equal('/start', res2.text); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await botWaiter; // wait until bot reply appears in storage Logger.botMessages(server.storage); assert.equal( 1, server.storage.botMessages.length, 'Message queue should contain one message!', ); await server.stop(); }); it('should provide bot`s messages to client', async () => { const { server, client } = await getServerAndClient(token); const message = client.makeMessage('/start'); const botWaiter = server.waitBotMessage(); const res = await client.sendMessage(message); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new TelegramBotEx(token, botOptions); attachMessageHandler(telegramBot); const res2 = await telegramBot.waitForReceiveUpdate(); assert.equal('/start', res2.text); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await botWaiter; const updates = await client.getUpdates(); Logger.serverUpdate(updates.result); assert.equal( 1, updates.result.length, 'Updates queue should contain one message!', ); await server.stop(); }); it('should message in response to /sendMessage', (done) => { getServerAndClient(token).then(({ server, client }) => { const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const bot = new TelegramBot(token, botOptions); bot.onText(/\/start/, async (msg) => { const chatId = msg.chat.id; if (!chatId) return; const reply = await bot.sendMessage(chatId, 'ololo #azaza', { reply_to_message_id: msg.message_id, reply_markup: { inline_keyboard: [[{text: 'foo', callback_data: 'bar'}]], }, }); const update = server.getUpdatesHistory(token).find((upd) => reply.message_id === upd.messageId); if (!isBotUpdate(update)) { assert.fail('Cannot find bot update with messageId porvided in response'); } assert.equal(update.message.text, reply.text); if (!isInlineKeyboard(update.message.reply_markup)) { assert.fail('Wrong keyboard type in stored update'); } assert.deepEqual(reply.reply_markup, update.message.reply_markup!); await server.stop(); await bot.stopPolling(); done(); }); return client.sendMessage(client.makeMessage('/start')); }).catch((err) => assert.fail(err)); }); it('waits user message', async () => { const { server, client } = await getServerAndClient(token); client.sendCommand(client.makeCommand('/start')); await server.waitUserMessage(); const history = await client.getUpdatesHistory(); assert.equal(history.length, 1); await server.stop(); }); it('should fully implement user-bot interaction', async () => { const { server, client } = await getServerAndClient(token); let message = client.makeMessage('/start'); const res = await client.sendMessage(message); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new TelegramBotEx(token, botOptions); attachMessageHandler(telegramBot); const updates = await client.getUpdates(); Logger.serverUpdate(updates.result); assert.equal( 1, updates.result.length, 'Updates queue should contain one message!', ); const markup = updates.result[0].message.reply_markup!; if (!isReplyKeyboard(markup) || !isCommonButton(markup.keyboard[0][0])) { throw new Error('No keyboard in update'); } message = client.makeMessage(markup.keyboard[0][0].text); await client.sendMessage(message); const updates2 = await client.getUpdates(); Logger.serverUpdate(updates2.result); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await server.stop(); assert.equal( 1, updates2.result.length, 'Updates queue should contain one message!', ); assert.equal( 'Hello, Masha!', updates2.result[0].message.text, 'Wrong greeting message!', ); }); it('should get updates only for respective client', async () => { const { server, client } = await getServerAndClient(token); const botOptions = {polling: true, baseApiUrl: server.config.apiURL}; const telegramBot = new TelegramBotEx(token, botOptions); attachMessageHandler(telegramBot); const client2 = server.getClient(token, {chatId: 2, firstName: 'Second User'}); await client.sendMessage(client.makeMessage('/start')); await client2.sendMessage(client2.makeMessage('/start')); const updates = await client.getUpdates(); const updates2 = await client2.getUpdates(); assert.equal(updates.result.length, 1); assert.equal(updates2.result.length, 1); await telegramBot.stopPolling(); await server.stop(); }); it('should get updates history', async () => { const { server, client } = await getServerAndClient(token); let message = client.makeMessage('/start'); const res = await client.sendMessage(message); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new TelegramBotEx(token, botOptions); attachMessageHandler(telegramBot); const updates = await client.getUpdates(); Logger.serverUpdate(updates.result); assert.equal( 1, updates.result.length, 'Updates queue should contain one message!', ); const markup = updates.result[0].message.reply_markup!; if (!isReplyKeyboard(markup) || !isCommonButton(markup.keyboard[0][0])) { throw new Error('No keyboard in update'); } message = client.makeMessage(markup.keyboard[0][0].text); await client.sendMessage(message); const updates2 = await client.getUpdates(); Logger.serverUpdate(updates2.result); assert.equal( 1, updates2.result.length, 'Updates queue should contain one message!', ); assert.equal( 'Hello, Masha!', updates2.result[0].message.text, 'Wrong greeting message!', ); const history = await client.getUpdatesHistory(); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await server.stop(); assert.equal(history.length, 4); history.forEach((item, index) => { assert.ok(item.time); assert.ok(item.botToken); assert.ok('message' in item && item.message); assert.ok(item.updateId); assert.ok(item.messageId); if (index > 0) { assert.isAbove(item.time, history[index - 1].time); } }); }); it('should allow messages deletion', async () => { const { server, client } = await getServerAndClient(token); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new DeleterBot(token, botOptions); let message = client.makeMessage('delete'); // Should be deleted const res = await client.sendMessage(message); assert.ok(res.ok); message = client.makeMessage('keep safe'); // Shouldn't be deleted const res2 = await client.sendMessage(message); assert.ok(res2.ok); await assertEventuallyTrue( 500, 'User messages count should become 1', () => server.storage.userMessages.length === 1, ); debugTest('Stopping polling'); await telegramBot.stopPolling(); await server.stop(); }); it('should receive user`s callbacks', async () => { const { server, client } = await getServerAndClient(token); const cb = client.makeCallbackQuery('somedata'); const res = await client.sendCallback(cb); await server.stop(); assert.equal(true, res.ok); }); it('should provide user`s callbacks to bot', async () => { const { server, client } = await getServerAndClient(token); const cb = client.makeCallbackQuery('somedata'); const res = await client.sendCallback(cb); assert.equal(true, res.ok); const botOptions = { polling: true, baseApiUrl: server.config.apiURL }; const telegramBot = new CallbackQBot(token, botOptions); const res2 = await telegramBot.waitForReceiveUpdate(); debugTest('Stopping polling'); await telegramBot.stopPolling(); debugTest('Polling stopped'); await server.stop(); assert.equal('somedata', res2.data); }); it('should handle message editing', async () => { const { server, client } = await getServerAndClient(token); const bot = new TelegramBot(token, {baseApiUrl: server.config.apiURL, polling: true}); bot.onText(/\/start/, (msg) => { const chatId = msg.from!.id; bot.sendMessage(chatId, 'Greetings'); }); bot.on('callback_query', (query) => { if (query.data === 'edit') { bot.editMessageText( 'Edited', {chat_id: query.message!.chat.id, message_id: query.message!.message_id}, ); } }); await client.sendCommand(client.makeCommand('/start')); const startUpdates = await client.getUpdates(); const botReply = startUpdates.result[0]; assert.exists(botReply); assert.equal(botReply.message.text, 'Greetings'); const cb = client.makeCallbackQuery('edit', {message: {message_id: botReply.messageId}}); await client.sendCallback(cb); await server.waitBotEdits(); const allUpdates = await client.getUpdatesHistory(); const targetUpdte = allUpdates.find((update) => update.messageId === botReply.messageId); assert.equal(targetUpdte && 'message' in targetUpdte && targetUpdte.message.text, 'Edited'); await bot.stopPolling(); await server.stop(); }); it('should remove messages on storeTimeout', async () => { const { server, client } = await getServerAndClient(token, { storeTimeout: 1, }); const message = client.makeMessage('/start'); await client.sendMessage(message); assert.equal(server.storage.userMessages.length, 1); debugTest('equal 1 ok'); await delay(2100); debugTest('waited for delay'); debugTest('server.storage.userMessages', server.storage.userMessages); assert.equal(server.storage.userMessages.length, 0); await server.stop(); }); });
the_stack
import { getIPGroup, isPrivate, isLocal, getNetwork, getIPBytes, getNetgroup, NETWORK, getBucketId, PEER_TYPE, } from '../../../src/utils'; import { DEFAULT_RANDOM_SECRET } from '../../../src/constants'; describe('utils/network', () => { const MAX_GROUP_NUM = 255; const MAX_NEW_BUCKETS = 128; const MAX_TRIED_BUCKETS = 64; const MAX_PEER_ADDRESSES = 65025; const secret = 3944604511; // Use fixed valued instead DEFAULT_RANDOM_SECRET for expectation const IPv4Address = '1.160.10.240'; const secondIPv4Address = '1.161.10.240'; const sourceIPv4Address = '1.165.10.240'; const privateAddress = '10.0.0.0'; const localAddress = '127.0.0.1'; describe('#getIPGroup', () => { it('should return first group when passing 0 in second argument', () => { const byte = getIPGroup(IPv4Address, 0); return expect(byte).toEqual(1); }); it('should throw an error for second argument greater than 3', () => { expect(() => getIPGroup(IPv4Address, 4)).toThrow('Invalid IP group.'); }); }); describe('#getIPBytes', () => { it('should return an object with property groupABytes', () => { return expect(getIPBytes(IPv4Address)).toHaveProperty('aBytes'); }); it('should return an object with property groupBBytes', () => { return expect(getIPBytes(IPv4Address)).toHaveProperty('bBytes'); }); it('should return an object with property groupCBytes', () => { return expect(getIPBytes(IPv4Address)).toHaveProperty('cBytes'); }); it('should return an object with property groupDBytes', () => { return expect(getIPBytes(IPv4Address)).toHaveProperty('dBytes'); }); }); describe('#isPrivate', () => { it('should return true for private IP address', () => { return expect(isPrivate(privateAddress)).toBe(true); }); }); describe('#isLocal', () => { it('should return true for local IP address', () => { return expect(isLocal(localAddress)).toBe(true); }); }); describe('#getNetwork', () => { it(`should return ${NETWORK.NET_IPV4} for IPv4 address`, () => { return expect(getNetwork(IPv4Address)).toEqual(NETWORK.NET_IPV4); }); it(`should return ${NETWORK.NET_PRIVATE} for private address`, () => { return expect(getNetwork(privateAddress)).toEqual(NETWORK.NET_PRIVATE); }); it(`should return ${NETWORK.NET_LOCAL} for local address`, () => { return expect(getNetwork(localAddress)).toEqual(NETWORK.NET_LOCAL); }); }); describe('#getNetgroup', () => { it(`should throw an error if network is equal to ${NETWORK.NET_OTHER}`, () => { expect(() => getNetgroup('wrong ipAddress', DEFAULT_RANDOM_SECRET)).toThrow( 'IP address is unsupported.', ); }); it('should return a number netgroup', () => { return expect(getNetgroup(IPv4Address, secret)).toEqual(expect.any(Number)); }); it('should return different netgroup for different addresses', () => { const anotherSecondIPv4Address = '1.161.10.240'; const firstNetgroup = getNetgroup(IPv4Address, secret); const secondNetgroup = getNetgroup(anotherSecondIPv4Address, secret); return expect(firstNetgroup).not.toEqual(secondNetgroup); }); it('should return same netgroup for unique local addresses', () => { const firstNetgroup = getNetgroup(localAddress, secret); const secondLocalAddress = '127.0.1.1'; const secondNetgroup = getNetgroup(secondLocalAddress, secret); return expect(firstNetgroup).toEqual(secondNetgroup); }); it('should return same netgroup for unique private addresses', () => { const firstNetgroup = getNetgroup(privateAddress, secret); const secondPrivateAddress = '10.0.0.1'; const secondNetgroup = getNetgroup(secondPrivateAddress, secret); return expect(firstNetgroup).toEqual(secondNetgroup); }); it('should return different netgroups for local and private addresses', () => { const firstNetgroup = getNetgroup(localAddress, secret); const secondNetgroup = getNetgroup(privateAddress, secret); return expect(firstNetgroup).not.toEqual(secondNetgroup); }); }); describe('#evictPeerRandomlyFromBucket', () => { it.todo('must return the evicted peer info'); }); describe('#expirePeerFromBucket', () => { describe('when bucket contains old peers', () => { it.todo('should return the evicted peer info'); }); describe('when bucket does not contains old peers', () => { it.todo('should return undefined'); }); }); describe('#getBucketId', () => { it('should return a bucket number', () => { expect( getBucketId({ secret, targetAddress: IPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }), ).toSatisfy((n: number) => n >= 0 && n <= MAX_NEW_BUCKETS); }); it('should return a bucket number with source address', () => { expect( getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: secondIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }), ).toSatisfy((n: number) => n >= 0 && n <= MAX_NEW_BUCKETS); }); it(`should throw an error if network is equal to ${NETWORK.NET_OTHER}`, () => { expect(() => getBucketId({ secret, targetAddress: 'wrong ipAddress', peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }), ).toThrow('IP address is unsupported.'); }); it('should return different buckets for different target addresses', () => { const anotherSecondIPv4Address = '1.161.10.240'; const firstBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: IPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondBucket = getBucketId({ secret, targetAddress: anotherSecondIPv4Address, sourceAddress: anotherSecondIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); expect(firstBucket).not.toEqual(secondBucket); }); it('should return same bucket for unique local target addresses', () => { const firstBucket = getBucketId({ secret, targetAddress: localAddress, sourceAddress: localAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondLocalAddress = '127.0.1.1'; const secondBucket = getBucketId({ secret, targetAddress: secondLocalAddress, sourceAddress: secondLocalAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); expect(firstBucket).toEqual(secondBucket); }); it('should return same bucket for unique private target addresses', () => { const firstBucket = getBucketId({ secret, targetAddress: privateAddress, sourceAddress: privateAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondPrivateAddress = '10.0.0.1'; const secondBucket = getBucketId({ secret, targetAddress: secondPrivateAddress, sourceAddress: secondPrivateAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); expect(firstBucket).toEqual(secondBucket); }); it('should return different buckets for local and private target addresses', () => { const firstBucket = getBucketId({ secret, targetAddress: localAddress, sourceAddress: localAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondBucket = getBucketId({ secret, targetAddress: privateAddress, sourceAddress: privateAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); expect(firstBucket).not.toEqual(secondBucket); }); it('should return the same bucket given random ip addresses in the same group for new peers', () => { const collectedBuckets = new Array(MAX_GROUP_NUM) .fill(0) .map(() => `61.26.254.${Math.floor(Math.random() * 256)}`) .map(address => getBucketId({ secret, targetAddress: address, sourceAddress: address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }), ); const firstBucket = collectedBuckets[0]; expect(collectedBuckets.every(bucket => bucket === firstBucket)).toBe(true); }); it('should return NaN if bucketCount is 0', () => { const bucketId = getBucketId({ secret, targetAddress: '61.26.254.123', sourceAddress: '61.26.254.123', peerType: PEER_TYPE.NEW_PEER, bucketCount: 0, }); expect(bucketId).toBeNaN(); }); it('should return different buckets for different target addresses given a single source address', () => { const firstBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: sourceIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondBucket = getBucketId({ secret, targetAddress: secondIPv4Address, sourceAddress: sourceIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); return expect(firstBucket).not.toEqual(secondBucket); }); it('should return different buckets for same target addresses given different source address', () => { const firstBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: sourceIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: secondIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); return expect(firstBucket).not.toEqual(secondBucket); }); it('should return different buckets for same target address and source address but different peerType', () => { const firstBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: sourceIPv4Address, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); const secondBucket = getBucketId({ secret, targetAddress: IPv4Address, sourceAddress: sourceIPv4Address, peerType: PEER_TYPE.TRIED_PEER, bucketCount: MAX_NEW_BUCKETS, }); return expect(firstBucket).not.toEqual(secondBucket); }); it('should return an even distribution of peers in each bucket given random ip addresses in different groups for tried peers', () => { const expectedPeerCountPerBucketLowerBound = (MAX_PEER_ADDRESSES / MAX_TRIED_BUCKETS) * 0.4; const expectedPeerCountPerBucketUpperBound = (MAX_PEER_ADDRESSES / MAX_TRIED_BUCKETS) * 1.7; const collectedBuckets = new Array(MAX_PEER_ADDRESSES).fill(0).reduce((prev: any) => { const targetAddress = `${Math.floor(Math.random() * 256)}.${Math.floor( Math.random() * 256, )}.254.1`; const bucket = getBucketId({ secret, targetAddress, sourceAddress: targetAddress, peerType: PEER_TYPE.TRIED_PEER, bucketCount: MAX_TRIED_BUCKETS, }); if (!prev[bucket]) { // eslint-disable-next-line no-param-reassign prev[bucket] = 0; } // eslint-disable-next-line no-param-reassign prev[bucket] += 1; return prev; }, {}); Object.values(collectedBuckets).forEach((bucketCount: any) => { expect(bucketCount).toBeGreaterThan(expectedPeerCountPerBucketLowerBound); expect(bucketCount).toBeLessThan(expectedPeerCountPerBucketUpperBound); }); }); // The bounds are more tolerant here due to our temporary solution to not include source IP changing the outcome of distribution it('should return an even distribution of peers in each bucket given random ip addresses in different groups for new peers', () => { const expectedPeerCountPerBucketLowerBound = (MAX_PEER_ADDRESSES / MAX_NEW_BUCKETS) * 0.2; const expectedPeerCountPerBucketUpperBound = (MAX_PEER_ADDRESSES / MAX_NEW_BUCKETS) * 2.7; const collectedBuckets = new Array(MAX_PEER_ADDRESSES).fill(0).reduce((prev: any) => { const targetAddress = `${Math.floor(Math.random() * 256)}.${Math.floor( Math.random() * 256, )}.254.1`; const bucket = getBucketId({ secret, targetAddress, sourceAddress: targetAddress, peerType: PEER_TYPE.NEW_PEER, bucketCount: MAX_NEW_BUCKETS, }); if (!prev[bucket]) { // eslint-disable-next-line no-param-reassign prev[bucket] = 0; } // eslint-disable-next-line no-param-reassign prev[bucket] += 1; return prev; }, {}); Object.values(collectedBuckets).forEach((bucketCount: any) => { expect(bucketCount).toBeGreaterThan(expectedPeerCountPerBucketLowerBound); expect(bucketCount).toBeLessThan(expectedPeerCountPerBucketUpperBound); }); }); }); });
the_stack
import * as coreClient from "@azure/core-client"; import * as coreAuth from "@azure/core-auth"; import * as Parameters from "./models/parameters"; import * as Mappers from "./models/mappers"; import { TeamCloudContext } from "./teamCloudContext"; import { TeamCloudOptionalParams, TeamCloudGetAdaptersOptionalParams, TeamCloudGetAdaptersResponse, TeamCloudGetComponentsOptionalParams, TeamCloudGetComponentsResponse, TeamCloudCreateComponentOptionalParams, TeamCloudCreateComponentResponse, TeamCloudGetComponentOptionalParams, TeamCloudGetComponentResponse, TeamCloudDeleteComponentOptionalParams, TeamCloudDeleteComponentResponse, TeamCloudGetComponentTasksOptionalParams, TeamCloudGetComponentTasksResponse, TeamCloudCreateComponentTaskOptionalParams, TeamCloudCreateComponentTaskResponse, TeamCloudGetComponentTaskOptionalParams, TeamCloudGetComponentTaskResponse, TeamCloudCancelComponentTaskOptionalParams, TeamCloudCancelComponentTaskResponse, TeamCloudReRunComponentTaskOptionalParams, TeamCloudReRunComponentTaskResponse, TeamCloudGetComponentTemplatesOptionalParams, TeamCloudGetComponentTemplatesResponse, TeamCloudGetComponentTemplateOptionalParams, TeamCloudGetComponentTemplateResponse, TeamCloudGetDeploymentScopesOptionalParams, TeamCloudGetDeploymentScopesResponse, TeamCloudCreateDeploymentScopeOptionalParams, TeamCloudCreateDeploymentScopeResponse, TeamCloudGetDeploymentScopeOptionalParams, TeamCloudGetDeploymentScopeResponse, TeamCloudUpdateDeploymentScopeOptionalParams, TeamCloudUpdateDeploymentScopeResponse, TeamCloudDeleteDeploymentScopeOptionalParams, TeamCloudDeleteDeploymentScopeResponse, TeamCloudInitializeAuthorizationOptionalParams, TeamCloudInitializeAuthorizationResponse, TeamCloudNegotiateSignalROptionalParams, TeamCloudGetAuditEntriesOptionalParams, TeamCloudGetAuditEntriesResponse, TeamCloudGetAuditEntryOptionalParams, TeamCloudGetAuditEntryResponse, TeamCloudGetAuditCommandsOptionalParams, TeamCloudGetAuditCommandsResponse, TeamCloudGetOrganizationsOptionalParams, TeamCloudGetOrganizationsResponse, TeamCloudCreateOrganizationOptionalParams, TeamCloudCreateOrganizationResponse, TeamCloudGetOrganizationOptionalParams, TeamCloudGetOrganizationResponse, TeamCloudDeleteOrganizationOptionalParams, TeamCloudDeleteOrganizationResponse, TeamCloudGetOrganizationUsersOptionalParams, TeamCloudGetOrganizationUsersResponse, TeamCloudCreateOrganizationUserOptionalParams, TeamCloudCreateOrganizationUserResponse, TeamCloudGetOrganizationUserOptionalParams, TeamCloudGetOrganizationUserResponse, TeamCloudUpdateOrganizationUserOptionalParams, TeamCloudUpdateOrganizationUserResponse, TeamCloudDeleteOrganizationUserOptionalParams, TeamCloudDeleteOrganizationUserResponse, TeamCloudGetOrganizationUserMeOptionalParams, TeamCloudGetOrganizationUserMeResponse, TeamCloudUpdateOrganizationUserMeOptionalParams, TeamCloudUpdateOrganizationUserMeResponse, TeamCloudGetProjectsOptionalParams, TeamCloudGetProjectsResponse, TeamCloudCreateProjectOptionalParams, TeamCloudCreateProjectResponse, TeamCloudGetProjectOptionalParams, TeamCloudGetProjectResponse, TeamCloudDeleteProjectOptionalParams, TeamCloudDeleteProjectResponse, TeamCloudGetProjectIdentitiesOptionalParams, TeamCloudGetProjectIdentitiesResponse, TeamCloudCreateProjectIdentityOptionalParams, TeamCloudCreateProjectIdentityResponse, TeamCloudGetProjectIdentityOptionalParams, TeamCloudGetProjectIdentityResponse, TeamCloudUpdateProjectIdentityOptionalParams, TeamCloudUpdateProjectIdentityResponse, TeamCloudDeleteProjectIdentityOptionalParams, TeamCloudDeleteProjectIdentityResponse, TeamCloudGetProjectTagsOptionalParams, TeamCloudGetProjectTagsResponse, TeamCloudCreateProjectTagOptionalParams, TeamCloudCreateProjectTagResponse, TeamCloudUpdateProjectTagOptionalParams, TeamCloudUpdateProjectTagResponse, TeamCloudGetProjectTagByKeyOptionalParams, TeamCloudGetProjectTagByKeyResponse, TeamCloudDeleteProjectTagOptionalParams, TeamCloudDeleteProjectTagResponse, TeamCloudGetProjectTemplatesOptionalParams, TeamCloudGetProjectTemplatesResponse, TeamCloudCreateProjectTemplateOptionalParams, TeamCloudCreateProjectTemplateResponse, TeamCloudGetProjectTemplateOptionalParams, TeamCloudGetProjectTemplateResponse, TeamCloudUpdateProjectTemplateOptionalParams, TeamCloudUpdateProjectTemplateResponse, TeamCloudDeleteProjectTemplateOptionalParams, TeamCloudDeleteProjectTemplateResponse, TeamCloudGetProjectUsersOptionalParams, TeamCloudGetProjectUsersResponse, TeamCloudCreateProjectUserOptionalParams, TeamCloudCreateProjectUserResponse, TeamCloudGetProjectUserOptionalParams, TeamCloudGetProjectUserResponse, TeamCloudUpdateProjectUserOptionalParams, TeamCloudUpdateProjectUserResponse, TeamCloudDeleteProjectUserOptionalParams, TeamCloudDeleteProjectUserResponse, TeamCloudGetProjectUserMeOptionalParams, TeamCloudGetProjectUserMeResponse, TeamCloudUpdateProjectUserMeOptionalParams, TeamCloudUpdateProjectUserMeResponse, TeamCloudGetSchedulesOptionalParams, TeamCloudGetSchedulesResponse, TeamCloudCreateScheduleOptionalParams, TeamCloudCreateScheduleResponse, TeamCloudGetScheduleOptionalParams, TeamCloudGetScheduleResponse, TeamCloudUpdateScheduleOptionalParams, TeamCloudUpdateScheduleResponse, TeamCloudRunScheduleOptionalParams, TeamCloudRunScheduleResponse, TeamCloudGetStatusOptionalParams, TeamCloudGetStatusResponse, TeamCloudGetProjectStatusOptionalParams, TeamCloudGetProjectStatusResponse, TeamCloudGetUserProjectsOptionalParams, TeamCloudGetUserProjectsResponse, TeamCloudGetUserProjectsMeOptionalParams, TeamCloudGetUserProjectsMeResponse } from "./models"; export class TeamCloud extends TeamCloudContext { /** * Initializes a new instance of the TeamCloud class. * @param credentials Subscription credentials which uniquely identify client subscription. * @param $host server parameter * @param options The parameter options */ constructor( credentials: coreAuth.TokenCredential, $host: string, options?: TeamCloudOptionalParams ) { super(credentials, $host, options); } /** * Gets all Adapters. * @param options The options parameters. */ getAdapters( options?: TeamCloudGetAdaptersOptionalParams ): Promise<TeamCloudGetAdaptersResponse> { return this.sendOperationRequest({ options }, getAdaptersOperationSpec); } /** * Gets all Components for a Project. * @param organizationId * @param projectId * @param options The options parameters. */ getComponents( organizationId: string, projectId: string, options?: TeamCloudGetComponentsOptionalParams ): Promise<TeamCloudGetComponentsResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getComponentsOperationSpec ); } /** * Creates a new Project Component. * @param organizationId * @param projectId * @param options The options parameters. */ createComponent( organizationId: string, projectId: string, options?: TeamCloudCreateComponentOptionalParams ): Promise<TeamCloudCreateComponentResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, createComponentOperationSpec ); } /** * Gets a Project Component. * @param componentId * @param organizationId * @param projectId * @param options The options parameters. */ getComponent( componentId: string | null, organizationId: string, projectId: string, options?: TeamCloudGetComponentOptionalParams ): Promise<TeamCloudGetComponentResponse> { return this.sendOperationRequest( { componentId, organizationId, projectId, options }, getComponentOperationSpec ); } /** * Deletes an existing Project Component. * @param componentId * @param organizationId * @param projectId * @param options The options parameters. */ deleteComponent( componentId: string | null, organizationId: string, projectId: string, options?: TeamCloudDeleteComponentOptionalParams ): Promise<TeamCloudDeleteComponentResponse> { return this.sendOperationRequest( { componentId, organizationId, projectId, options }, deleteComponentOperationSpec ); } /** * Gets all Component Tasks. * @param organizationId * @param projectId * @param componentId * @param options The options parameters. */ getComponentTasks( organizationId: string, projectId: string, componentId: string | null, options?: TeamCloudGetComponentTasksOptionalParams ): Promise<TeamCloudGetComponentTasksResponse> { return this.sendOperationRequest( { organizationId, projectId, componentId, options }, getComponentTasksOperationSpec ); } /** * Creates a new Project Component Task. * @param organizationId * @param projectId * @param componentId * @param options The options parameters. */ createComponentTask( organizationId: string, projectId: string, componentId: string | null, options?: TeamCloudCreateComponentTaskOptionalParams ): Promise<TeamCloudCreateComponentTaskResponse> { return this.sendOperationRequest( { organizationId, projectId, componentId, options }, createComponentTaskOperationSpec ); } /** * Gets the Component Task. * @param taskId * @param organizationId * @param projectId * @param componentId * @param options The options parameters. */ getComponentTask( taskId: string | null, organizationId: string, projectId: string, componentId: string | null, options?: TeamCloudGetComponentTaskOptionalParams ): Promise<TeamCloudGetComponentTaskResponse> { return this.sendOperationRequest( { taskId, organizationId, projectId, componentId, options }, getComponentTaskOperationSpec ); } /** * Rerun a Project Component Task. * @param organizationId * @param projectId * @param componentId * @param taskId * @param options The options parameters. */ cancelComponentTask( organizationId: string, projectId: string, componentId: string | null, taskId: string | null, options?: TeamCloudCancelComponentTaskOptionalParams ): Promise<TeamCloudCancelComponentTaskResponse> { return this.sendOperationRequest( { organizationId, projectId, componentId, taskId, options }, cancelComponentTaskOperationSpec ); } /** * Cancel an active Project Component Task. * @param organizationId * @param projectId * @param componentId * @param taskId * @param options The options parameters. */ reRunComponentTask( organizationId: string, projectId: string, componentId: string | null, taskId: string | null, options?: TeamCloudReRunComponentTaskOptionalParams ): Promise<TeamCloudReRunComponentTaskResponse> { return this.sendOperationRequest( { organizationId, projectId, componentId, taskId, options }, reRunComponentTaskOperationSpec ); } /** * Gets all Component Templates for a Project. * @param organizationId * @param projectId * @param options The options parameters. */ getComponentTemplates( organizationId: string, projectId: string, options?: TeamCloudGetComponentTemplatesOptionalParams ): Promise<TeamCloudGetComponentTemplatesResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getComponentTemplatesOperationSpec ); } /** * Gets the Component Template. * @param id * @param organizationId * @param projectId * @param options The options parameters. */ getComponentTemplate( id: string | null, organizationId: string, projectId: string, options?: TeamCloudGetComponentTemplateOptionalParams ): Promise<TeamCloudGetComponentTemplateResponse> { return this.sendOperationRequest( { id, organizationId, projectId, options }, getComponentTemplateOperationSpec ); } /** * Gets all Deployment Scopes. * @param organizationId * @param options The options parameters. */ getDeploymentScopes( organizationId: string, options?: TeamCloudGetDeploymentScopesOptionalParams ): Promise<TeamCloudGetDeploymentScopesResponse> { return this.sendOperationRequest( { organizationId, options }, getDeploymentScopesOperationSpec ); } /** * Creates a new Deployment Scope. * @param organizationId * @param options The options parameters. */ createDeploymentScope( organizationId: string, options?: TeamCloudCreateDeploymentScopeOptionalParams ): Promise<TeamCloudCreateDeploymentScopeResponse> { return this.sendOperationRequest( { organizationId, options }, createDeploymentScopeOperationSpec ); } /** * Gets a Deployment Scope. * @param organizationId * @param deploymentScopeId * @param options The options parameters. */ getDeploymentScope( organizationId: string, deploymentScopeId: string, options?: TeamCloudGetDeploymentScopeOptionalParams ): Promise<TeamCloudGetDeploymentScopeResponse> { return this.sendOperationRequest( { organizationId, deploymentScopeId, options }, getDeploymentScopeOperationSpec ); } /** * Updates an existing Deployment Scope. * @param organizationId * @param deploymentScopeId * @param options The options parameters. */ updateDeploymentScope( organizationId: string, deploymentScopeId: string, options?: TeamCloudUpdateDeploymentScopeOptionalParams ): Promise<TeamCloudUpdateDeploymentScopeResponse> { return this.sendOperationRequest( { organizationId, deploymentScopeId, options }, updateDeploymentScopeOperationSpec ); } /** * Deletes a Deployment Scope. * @param organizationId * @param deploymentScopeId * @param options The options parameters. */ deleteDeploymentScope( organizationId: string, deploymentScopeId: string, options?: TeamCloudDeleteDeploymentScopeOptionalParams ): Promise<TeamCloudDeleteDeploymentScopeResponse> { return this.sendOperationRequest( { organizationId, deploymentScopeId, options }, deleteDeploymentScopeOperationSpec ); } /** * Initialize a new authorization session for a deployment scope. * @param organizationId * @param deploymentScopeId * @param options The options parameters. */ initializeAuthorization( organizationId: string, deploymentScopeId: string, options?: TeamCloudInitializeAuthorizationOptionalParams ): Promise<TeamCloudInitializeAuthorizationResponse> { return this.sendOperationRequest( { organizationId, deploymentScopeId, options }, initializeAuthorizationOperationSpec ); } /** * Negotiates the SignalR connection. * @param organizationId * @param projectId * @param options The options parameters. */ negotiateSignalR( organizationId: string, projectId: string, options?: TeamCloudNegotiateSignalROptionalParams ): Promise<void> { return this.sendOperationRequest( { organizationId, projectId, options }, negotiateSignalROperationSpec ); } /** * Gets all audit entries. * @param organizationId * @param options The options parameters. */ getAuditEntries( organizationId: string, options?: TeamCloudGetAuditEntriesOptionalParams ): Promise<TeamCloudGetAuditEntriesResponse> { return this.sendOperationRequest( { organizationId, options }, getAuditEntriesOperationSpec ); } /** * Gets an audit entry. * @param commandId * @param organizationId * @param options The options parameters. */ getAuditEntry( commandId: string, organizationId: string, options?: TeamCloudGetAuditEntryOptionalParams ): Promise<TeamCloudGetAuditEntryResponse> { return this.sendOperationRequest( { commandId, organizationId, options }, getAuditEntryOperationSpec ); } /** * Gets all auditable commands. * @param organizationId * @param options The options parameters. */ getAuditCommands( organizationId: string, options?: TeamCloudGetAuditCommandsOptionalParams ): Promise<TeamCloudGetAuditCommandsResponse> { return this.sendOperationRequest( { organizationId, options }, getAuditCommandsOperationSpec ); } /** * Gets all Organizations. * @param options The options parameters. */ getOrganizations( options?: TeamCloudGetOrganizationsOptionalParams ): Promise<TeamCloudGetOrganizationsResponse> { return this.sendOperationRequest( { options }, getOrganizationsOperationSpec ); } /** * Creates a new Organization. * @param options The options parameters. */ createOrganization( options?: TeamCloudCreateOrganizationOptionalParams ): Promise<TeamCloudCreateOrganizationResponse> { return this.sendOperationRequest( { options }, createOrganizationOperationSpec ); } /** * Gets an Organization. * @param organizationId * @param options The options parameters. */ getOrganization( organizationId: string, options?: TeamCloudGetOrganizationOptionalParams ): Promise<TeamCloudGetOrganizationResponse> { return this.sendOperationRequest( { organizationId, options }, getOrganizationOperationSpec ); } /** * Deletes an existing Organization. * @param organizationId * @param options The options parameters. */ deleteOrganization( organizationId: string, options?: TeamCloudDeleteOrganizationOptionalParams ): Promise<TeamCloudDeleteOrganizationResponse> { return this.sendOperationRequest( { organizationId, options }, deleteOrganizationOperationSpec ); } /** * Gets all Users. * @param organizationId * @param options The options parameters. */ getOrganizationUsers( organizationId: string, options?: TeamCloudGetOrganizationUsersOptionalParams ): Promise<TeamCloudGetOrganizationUsersResponse> { return this.sendOperationRequest( { organizationId, options }, getOrganizationUsersOperationSpec ); } /** * Creates a new User. * @param organizationId * @param options The options parameters. */ createOrganizationUser( organizationId: string, options?: TeamCloudCreateOrganizationUserOptionalParams ): Promise<TeamCloudCreateOrganizationUserResponse> { return this.sendOperationRequest( { organizationId, options }, createOrganizationUserOperationSpec ); } /** * Gets a User. * @param userId * @param organizationId * @param options The options parameters. */ getOrganizationUser( userId: string | null, organizationId: string, options?: TeamCloudGetOrganizationUserOptionalParams ): Promise<TeamCloudGetOrganizationUserResponse> { return this.sendOperationRequest( { userId, organizationId, options }, getOrganizationUserOperationSpec ); } /** * Updates an existing User. * @param userId * @param organizationId * @param options The options parameters. */ updateOrganizationUser( userId: string | null, organizationId: string, options?: TeamCloudUpdateOrganizationUserOptionalParams ): Promise<TeamCloudUpdateOrganizationUserResponse> { return this.sendOperationRequest( { userId, organizationId, options }, updateOrganizationUserOperationSpec ); } /** * Deletes an existing User. * @param userId * @param organizationId * @param options The options parameters. */ deleteOrganizationUser( userId: string | null, organizationId: string, options?: TeamCloudDeleteOrganizationUserOptionalParams ): Promise<TeamCloudDeleteOrganizationUserResponse> { return this.sendOperationRequest( { userId, organizationId, options }, deleteOrganizationUserOperationSpec ); } /** * Gets a User A User matching the current authenticated user. * @param organizationId * @param options The options parameters. */ getOrganizationUserMe( organizationId: string, options?: TeamCloudGetOrganizationUserMeOptionalParams ): Promise<TeamCloudGetOrganizationUserMeResponse> { return this.sendOperationRequest( { organizationId, options }, getOrganizationUserMeOperationSpec ); } /** * Updates an existing User. * @param organizationId * @param options The options parameters. */ updateOrganizationUserMe( organizationId: string, options?: TeamCloudUpdateOrganizationUserMeOptionalParams ): Promise<TeamCloudUpdateOrganizationUserMeResponse> { return this.sendOperationRequest( { organizationId, options }, updateOrganizationUserMeOperationSpec ); } /** * Gets all Projects. * @param organizationId * @param options The options parameters. */ getProjects( organizationId: string, options?: TeamCloudGetProjectsOptionalParams ): Promise<TeamCloudGetProjectsResponse> { return this.sendOperationRequest( { organizationId, options }, getProjectsOperationSpec ); } /** * Creates a new Project. * @param organizationId * @param options The options parameters. */ createProject( organizationId: string, options?: TeamCloudCreateProjectOptionalParams ): Promise<TeamCloudCreateProjectResponse> { return this.sendOperationRequest( { organizationId, options }, createProjectOperationSpec ); } /** * Gets a Project. * @param projectId * @param organizationId * @param options The options parameters. */ getProject( projectId: string, organizationId: string, options?: TeamCloudGetProjectOptionalParams ): Promise<TeamCloudGetProjectResponse> { return this.sendOperationRequest( { projectId, organizationId, options }, getProjectOperationSpec ); } /** * Deletes a Project. * @param projectId * @param organizationId * @param options The options parameters. */ deleteProject( projectId: string, organizationId: string, options?: TeamCloudDeleteProjectOptionalParams ): Promise<TeamCloudDeleteProjectResponse> { return this.sendOperationRequest( { projectId, organizationId, options }, deleteProjectOperationSpec ); } /** * Gets all Project Identities. * @param organizationId * @param projectId * @param options The options parameters. */ getProjectIdentities( organizationId: string, projectId: string, options?: TeamCloudGetProjectIdentitiesOptionalParams ): Promise<TeamCloudGetProjectIdentitiesResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getProjectIdentitiesOperationSpec ); } /** * Creates a new Project Identity. * @param organizationId * @param projectId * @param options The options parameters. */ createProjectIdentity( organizationId: string, projectId: string, options?: TeamCloudCreateProjectIdentityOptionalParams ): Promise<TeamCloudCreateProjectIdentityResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, createProjectIdentityOperationSpec ); } /** * Gets a Project Identity. * @param projectIdentityId * @param organizationId * @param projectId * @param options The options parameters. */ getProjectIdentity( projectIdentityId: string | null, organizationId: string, projectId: string, options?: TeamCloudGetProjectIdentityOptionalParams ): Promise<TeamCloudGetProjectIdentityResponse> { return this.sendOperationRequest( { projectIdentityId, organizationId, projectId, options }, getProjectIdentityOperationSpec ); } /** * Updates an existing Project Identity. * @param projectIdentityId * @param organizationId * @param projectId * @param options The options parameters. */ updateProjectIdentity( projectIdentityId: string | null, organizationId: string, projectId: string, options?: TeamCloudUpdateProjectIdentityOptionalParams ): Promise<TeamCloudUpdateProjectIdentityResponse> { return this.sendOperationRequest( { projectIdentityId, organizationId, projectId, options }, updateProjectIdentityOperationSpec ); } /** * Deletes a Project Identity. * @param projectIdentityId * @param organizationId * @param projectId * @param options The options parameters. */ deleteProjectIdentity( projectIdentityId: string | null, organizationId: string, projectId: string, options?: TeamCloudDeleteProjectIdentityOptionalParams ): Promise<TeamCloudDeleteProjectIdentityResponse> { return this.sendOperationRequest( { projectIdentityId, organizationId, projectId, options }, deleteProjectIdentityOperationSpec ); } /** * Gets all Tags for a Project. * @param organizationId * @param projectId * @param options The options parameters. */ getProjectTags( organizationId: string, projectId: string, options?: TeamCloudGetProjectTagsOptionalParams ): Promise<TeamCloudGetProjectTagsResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getProjectTagsOperationSpec ); } /** * Creates a new Project Tag. * @param organizationId * @param projectId * @param options The options parameters. */ createProjectTag( organizationId: string, projectId: string, options?: TeamCloudCreateProjectTagOptionalParams ): Promise<TeamCloudCreateProjectTagResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, createProjectTagOperationSpec ); } /** * Updates an existing Project Tag. * @param organizationId * @param projectId * @param options The options parameters. */ updateProjectTag( organizationId: string, projectId: string, options?: TeamCloudUpdateProjectTagOptionalParams ): Promise<TeamCloudUpdateProjectTagResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, updateProjectTagOperationSpec ); } /** * Gets a Project Tag by Key. * @param tagKey * @param organizationId * @param projectId * @param options The options parameters. */ getProjectTagByKey( tagKey: string | null, organizationId: string, projectId: string, options?: TeamCloudGetProjectTagByKeyOptionalParams ): Promise<TeamCloudGetProjectTagByKeyResponse> { return this.sendOperationRequest( { tagKey, organizationId, projectId, options }, getProjectTagByKeyOperationSpec ); } /** * Deletes an existing Project Tag. * @param tagKey * @param organizationId * @param projectId * @param options The options parameters. */ deleteProjectTag( tagKey: string | null, organizationId: string, projectId: string, options?: TeamCloudDeleteProjectTagOptionalParams ): Promise<TeamCloudDeleteProjectTagResponse> { return this.sendOperationRequest( { tagKey, organizationId, projectId, options }, deleteProjectTagOperationSpec ); } /** * Gets all Project Templates. * @param organizationId * @param options The options parameters. */ getProjectTemplates( organizationId: string, options?: TeamCloudGetProjectTemplatesOptionalParams ): Promise<TeamCloudGetProjectTemplatesResponse> { return this.sendOperationRequest( { organizationId, options }, getProjectTemplatesOperationSpec ); } /** * Creates a new Project Template. * @param organizationId * @param options The options parameters. */ createProjectTemplate( organizationId: string, options?: TeamCloudCreateProjectTemplateOptionalParams ): Promise<TeamCloudCreateProjectTemplateResponse> { return this.sendOperationRequest( { organizationId, options }, createProjectTemplateOperationSpec ); } /** * Gets a Project Template. * @param projectTemplateId * @param organizationId * @param options The options parameters. */ getProjectTemplate( projectTemplateId: string | null, organizationId: string, options?: TeamCloudGetProjectTemplateOptionalParams ): Promise<TeamCloudGetProjectTemplateResponse> { return this.sendOperationRequest( { projectTemplateId, organizationId, options }, getProjectTemplateOperationSpec ); } /** * Updates an existing Project Template. * @param projectTemplateId * @param organizationId * @param options The options parameters. */ updateProjectTemplate( projectTemplateId: string | null, organizationId: string, options?: TeamCloudUpdateProjectTemplateOptionalParams ): Promise<TeamCloudUpdateProjectTemplateResponse> { return this.sendOperationRequest( { projectTemplateId, organizationId, options }, updateProjectTemplateOperationSpec ); } /** * Deletes a Project Template. * @param projectTemplateId * @param organizationId * @param options The options parameters. */ deleteProjectTemplate( projectTemplateId: string | null, organizationId: string, options?: TeamCloudDeleteProjectTemplateOptionalParams ): Promise<TeamCloudDeleteProjectTemplateResponse> { return this.sendOperationRequest( { projectTemplateId, organizationId, options }, deleteProjectTemplateOperationSpec ); } /** * Gets all Users for a Project. * @param organizationId * @param projectId * @param options The options parameters. */ getProjectUsers( organizationId: string, projectId: string, options?: TeamCloudGetProjectUsersOptionalParams ): Promise<TeamCloudGetProjectUsersResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getProjectUsersOperationSpec ); } /** * Creates a new Project User * @param organizationId * @param projectId * @param options The options parameters. */ createProjectUser( organizationId: string, projectId: string, options?: TeamCloudCreateProjectUserOptionalParams ): Promise<TeamCloudCreateProjectUserResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, createProjectUserOperationSpec ); } /** * Gets a Project User by ID or email address. * @param userId * @param organizationId * @param projectId * @param options The options parameters. */ getProjectUser( userId: string | null, organizationId: string, projectId: string, options?: TeamCloudGetProjectUserOptionalParams ): Promise<TeamCloudGetProjectUserResponse> { return this.sendOperationRequest( { userId, organizationId, projectId, options }, getProjectUserOperationSpec ); } /** * Updates an existing Project User. * @param userId * @param organizationId * @param projectId * @param options The options parameters. */ updateProjectUser( userId: string | null, organizationId: string, projectId: string, options?: TeamCloudUpdateProjectUserOptionalParams ): Promise<TeamCloudUpdateProjectUserResponse> { return this.sendOperationRequest( { userId, organizationId, projectId, options }, updateProjectUserOperationSpec ); } /** * Deletes an existing Project User. * @param userId * @param organizationId * @param projectId * @param options The options parameters. */ deleteProjectUser( userId: string | null, organizationId: string, projectId: string, options?: TeamCloudDeleteProjectUserOptionalParams ): Promise<TeamCloudDeleteProjectUserResponse> { return this.sendOperationRequest( { userId, organizationId, projectId, options }, deleteProjectUserOperationSpec ); } /** * Gets a Project User for the calling user. * @param organizationId * @param projectId * @param options The options parameters. */ getProjectUserMe( organizationId: string, projectId: string, options?: TeamCloudGetProjectUserMeOptionalParams ): Promise<TeamCloudGetProjectUserMeResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getProjectUserMeOperationSpec ); } /** * Updates an existing Project User. * @param organizationId * @param projectId * @param options The options parameters. */ updateProjectUserMe( organizationId: string, projectId: string, options?: TeamCloudUpdateProjectUserMeOptionalParams ): Promise<TeamCloudUpdateProjectUserMeResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, updateProjectUserMeOperationSpec ); } /** * Gets all Schedule. * @param organizationId * @param projectId * @param options The options parameters. */ getSchedules( organizationId: string, projectId: string, options?: TeamCloudGetSchedulesOptionalParams ): Promise<TeamCloudGetSchedulesResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, getSchedulesOperationSpec ); } /** * Creates a new Project Schedule. * @param organizationId * @param projectId * @param options The options parameters. */ createSchedule( organizationId: string, projectId: string, options?: TeamCloudCreateScheduleOptionalParams ): Promise<TeamCloudCreateScheduleResponse> { return this.sendOperationRequest( { organizationId, projectId, options }, createScheduleOperationSpec ); } /** * Gets the Schedule. * @param scheduleId * @param organizationId * @param projectId * @param options The options parameters. */ getSchedule( scheduleId: string | null, organizationId: string, projectId: string, options?: TeamCloudGetScheduleOptionalParams ): Promise<TeamCloudGetScheduleResponse> { return this.sendOperationRequest( { scheduleId, organizationId, projectId, options }, getScheduleOperationSpec ); } /** * Updates a Project Schedule. * @param scheduleId * @param organizationId * @param projectId * @param options The options parameters. */ updateSchedule( scheduleId: string | null, organizationId: string, projectId: string, options?: TeamCloudUpdateScheduleOptionalParams ): Promise<TeamCloudUpdateScheduleResponse> { return this.sendOperationRequest( { scheduleId, organizationId, projectId, options }, updateScheduleOperationSpec ); } /** * Runs a Project Schedule. * @param scheduleId * @param organizationId * @param projectId * @param options The options parameters. */ runSchedule( scheduleId: string | null, organizationId: string, projectId: string, options?: TeamCloudRunScheduleOptionalParams ): Promise<TeamCloudRunScheduleResponse> { return this.sendOperationRequest( { scheduleId, organizationId, projectId, options }, runScheduleOperationSpec ); } /** * Gets the status of a long-running operation. * @param trackingId * @param organizationId * @param options The options parameters. */ getStatus( trackingId: string, organizationId: string, options?: TeamCloudGetStatusOptionalParams ): Promise<TeamCloudGetStatusResponse> { return this.sendOperationRequest( { trackingId, organizationId, options }, getStatusOperationSpec ); } /** * Gets the status of a long-running operation. * @param projectId * @param trackingId * @param organizationId * @param options The options parameters. */ getProjectStatus( projectId: string, trackingId: string, organizationId: string, options?: TeamCloudGetProjectStatusOptionalParams ): Promise<TeamCloudGetProjectStatusResponse> { return this.sendOperationRequest( { projectId, trackingId, organizationId, options }, getProjectStatusOperationSpec ); } /** * Gets all Projects for a User. * @param organizationId * @param userId * @param options The options parameters. */ getUserProjects( organizationId: string, userId: string | null, options?: TeamCloudGetUserProjectsOptionalParams ): Promise<TeamCloudGetUserProjectsResponse> { return this.sendOperationRequest( { organizationId, userId, options }, getUserProjectsOperationSpec ); } /** * Gets all Projects for a User. * @param organizationId * @param options The options parameters. */ getUserProjectsMe( organizationId: string, options?: TeamCloudGetUserProjectsMeOptionalParams ): Promise<TeamCloudGetUserProjectsMeResponse> { return this.sendOperationRequest( { organizationId, options }, getUserProjectsMeOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getAdaptersOperationSpec: coreClient.OperationSpec = { path: "/adapters", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AdapterInformationListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const getComponentsOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, queryParameters: [Parameters.deleted], urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const createComponentOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ComponentDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getComponentOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId ], headerParameters: [Parameters.accept], serializer }; const deleteComponentOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 204: { bodyMapper: Mappers.ComponentDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId ], headerParameters: [Parameters.accept], serializer }; const getComponentTasksOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}/tasks", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentTaskListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId ], headerParameters: [Parameters.accept], serializer }; const createComponentTaskOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}/tasks", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ComponentTaskDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body1, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getComponentTaskOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}/tasks/{taskId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentTaskDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId, Parameters.taskId ], headerParameters: [Parameters.accept], serializer }; const cancelComponentTaskOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}/tasks/{taskId}/cancel", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ComponentTaskDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId, Parameters.taskId ], headerParameters: [Parameters.accept], serializer }; const reRunComponentTaskOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/components/{componentId}/tasks/{taskId}/rerun", httpMethod: "PUT", responses: { 201: { bodyMapper: Mappers.ComponentTaskDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.componentId, Parameters.taskId ], headerParameters: [Parameters.accept], serializer }; const getComponentTemplatesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/templates", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentTemplateListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const getComponentTemplateOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/templates/{id}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ComponentTemplateDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.id ], headerParameters: [Parameters.accept], serializer }; const getDeploymentScopesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentScopeListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const createDeploymentScopeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.DeploymentScopeDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body2, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDeploymentScopeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes/{deploymentScopeId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentScopeDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.deploymentScopeId ], headerParameters: [Parameters.accept], serializer }; const updateDeploymentScopeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes/{deploymentScopeId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.DeploymentScopeDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body3, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.deploymentScopeId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteDeploymentScopeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes/{deploymentScopeId}", httpMethod: "DELETE", responses: { 204: { bodyMapper: Mappers.DeploymentScopeDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.deploymentScopeId ], headerParameters: [Parameters.accept], serializer }; const initializeAuthorizationOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/scopes/{deploymentScopeId}/authorize/initialize", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeploymentScopeDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.deploymentScopeId ], headerParameters: [Parameters.accept], serializer }; const negotiateSignalROperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/negotiate", httpMethod: "POST", responses: { 200: {}, 401: {}, 403: {} }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], serializer }; const getAuditEntriesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/audit", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.CommandAuditEntityListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, queryParameters: [Parameters.timeRange, Parameters.commands], urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const getAuditEntryOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/audit/{commandId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.CommandAuditEntityDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, queryParameters: [Parameters.expand], urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.commandId ], headerParameters: [Parameters.accept], serializer }; const getAuditCommandsOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/audit/commands", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StringListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const getOrganizationsOperationSpec: coreClient.OperationSpec = { path: "/orgs", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OrganizationListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept], serializer }; const createOrganizationOperationSpec: coreClient.OperationSpec = { path: "/orgs", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.OrganizationDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body4, urlParameters: [Parameters.$host], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOrganizationOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OrganizationDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const deleteOrganizationOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const getOrganizationUsersOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const createOrganizationUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.UserDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body5, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOrganizationUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users/{userId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.userId ], headerParameters: [Parameters.accept], serializer }; const updateOrganizationUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users/{userId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body6, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.userId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOrganizationUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users/{userId}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 204: { bodyMapper: Mappers.UserDataResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.userId ], headerParameters: [Parameters.accept], serializer }; const getOrganizationUserMeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/me", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const updateOrganizationUserMeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/me", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body6, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectsOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const createProjectOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ProjectDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body7, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const deleteProjectOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const getProjectIdentitiesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/identities", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectIdentityListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const createProjectIdentityOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/identities", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ProjectIdentityDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body8, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectIdentityOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/identities/{projectIdentityId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectIdentityDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.projectIdentityId ], headerParameters: [Parameters.accept], serializer }; const updateProjectIdentityOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/identities/{projectIdentityId}", httpMethod: "PUT", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body9, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.projectIdentityId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteProjectIdentityOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/identities/{projectIdentityId}", httpMethod: "DELETE", responses: { 204: { bodyMapper: Mappers.ProjectIdentityDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.projectIdentityId ], headerParameters: [Parameters.accept], serializer }; const getProjectTagsOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/tags", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StringDictionaryDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const createProjectTagOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/tags", httpMethod: "POST", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body10, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateProjectTagOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/tags", httpMethod: "PUT", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body10, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectTagByKeyOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/tags/{tagKey}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StringDictionaryDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.tagKey ], headerParameters: [Parameters.accept], serializer }; const deleteProjectTagOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/tags/{tagKey}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.tagKey ], headerParameters: [Parameters.accept], serializer }; const getProjectTemplatesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/templates", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectTemplateListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer }; const createProjectTemplateOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/templates", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ProjectTemplateDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body11, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectTemplateOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/templates/{projectTemplateId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectTemplateDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectTemplateId ], headerParameters: [Parameters.accept], serializer }; const updateProjectTemplateOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/templates/{projectTemplateId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ProjectTemplateDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body12, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectTemplateId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteProjectTemplateOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/templates/{projectTemplateId}", httpMethod: "DELETE", responses: { 204: { bodyMapper: Mappers.ProjectTemplateDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectTemplateId ], headerParameters: [Parameters.accept], serializer }; const getProjectUsersOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const createProjectUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.UserDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body5, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getProjectUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users/{userId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.userId ], headerParameters: [Parameters.accept], serializer }; const updateProjectUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users/{userId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body6, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.userId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteProjectUserOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users/{userId}", httpMethod: "DELETE", responses: { 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.userId ], headerParameters: [Parameters.accept], serializer }; const getProjectUserMeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users/me", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const updateProjectUserMeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/users/me", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.UserDataResult }, 202: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body6, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getSchedulesOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/schedules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScheduleListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {} }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept], serializer }; const createScheduleOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/schedules", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.ScheduleDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body13, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getScheduleOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/schedules/{scheduleId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScheduleDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.scheduleId ], headerParameters: [Parameters.accept], serializer }; const updateScheduleOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/schedules/{scheduleId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ScheduleDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult }, 409: { bodyMapper: Mappers.ErrorResult } }, requestBody: Parameters.body14, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.scheduleId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const runScheduleOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/schedules/{scheduleId}/run", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ScheduleDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.scheduleId ], headerParameters: [Parameters.accept], serializer }; const getStatusOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/status/{trackingId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StatusResult }, 202: { bodyMapper: Mappers.StatusResult }, 302: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.trackingId ], headerParameters: [Parameters.accept], serializer }; const getProjectStatusOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/projects/{projectId}/status/{trackingId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StatusResult }, 202: { bodyMapper: Mappers.StatusResult }, 302: { bodyMapper: Mappers.StatusResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.projectId, Parameters.trackingId ], headerParameters: [Parameters.accept], serializer }; const getUserProjectsOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/users/{userId}/projects", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [ Parameters.$host, Parameters.organizationId, Parameters.userId ], headerParameters: [Parameters.accept], serializer }; const getUserProjectsMeOperationSpec: coreClient.OperationSpec = { path: "/orgs/{organizationId}/me/projects", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ProjectListDataResult }, 400: { bodyMapper: Mappers.ErrorResult }, 401: {}, 403: {}, 404: { bodyMapper: Mappers.ErrorResult } }, urlParameters: [Parameters.$host, Parameters.organizationId], headerParameters: [Parameters.accept], serializer };
the_stack
import * as actions from '../actions'; import {reducers} from './debugger_reducers'; import {CodeLocationType, DataLoadState} from './debugger_types'; import { createDebuggerGraphsState, createDebuggerSourceCodeState, createDebuggerState, createTestGraphOpInfo, createTestStackFrame, createDebuggerGraphExecutionsState, } from '../testing'; describe('Debugger reducers', () => { describe('graphOpFocused', () => { it('sets focusedOp in graphs state from empty state', () => { const state = createDebuggerState(); const nextState = reducers( state, actions.graphOpFocused({graph_id: 'g2', op_name: 'TestOp_12'}) ); expect(nextState.graphs.focusedOp).toEqual({ graphId: 'g2', opName: 'TestOp_12', }); expect(nextState.codeLocationFocusType).toBe( CodeLocationType.GRAPH_OP_CREATION ); }); it('sets focusedOp in graphs state from non-empty state', () => { const state = createDebuggerState({ graphs: createDebuggerGraphsState({ focusedOp: { graphId: 'g1', opName: 'TestOp_1', }, }), }); const nextState = reducers( state, actions.graphOpFocused({graph_id: 'g2', op_name: 'TestOp_12'}) ); expect(nextState.graphs.focusedOp).toEqual({ graphId: 'g2', opName: 'TestOp_12', }); expect(nextState.codeLocationFocusType).toBe( CodeLocationType.GRAPH_OP_CREATION ); }); for (const [ stickToBottommostFrameInFocusedFile, stackFrameIsLoaded, expectedLineno, expectedFunctionName, ] of [ [false, false, 20, 'main'], [false, true, 20, 'main'], [true, false, 20, 'main'], [true, true, 30, 'helper'], ] as Array<[boolean, boolean, number, string]>) { it( `focusLineSpec sticking behavior: ` + `stickToBottommostFrameInFocusedFile=` + `${stickToBottommostFrameInFocusedFile}; ` + `stackFrameIsLoaded=${stackFrameIsLoaded}`, () => { const stackFrame0 = createTestStackFrame({ file_path: 'main.py', lineno: 10, function_name: '<module>', }); const stackFrame1 = createTestStackFrame({ file_path: 'main.py', lineno: 20, function_name: 'main', }); const stackFrame2 = createTestStackFrame({ file_path: 'main.py', lineno: 30, function_name: 'helper', }); const state = createDebuggerState({ graphs: createDebuggerGraphsState({ ops: { g1: new Map([ [ 'op1', createTestGraphOpInfo({ stack_frame_ids: ['s0', 's1'], }), ], [ 'op2', createTestGraphOpInfo({ stack_frame_ids: ['s0', 's2'], }), ], ]), }, focusedOp: { graphId: 'g1', opName: 'op1', }, }), stackFrames: stackFrameIsLoaded ? { s0: stackFrame0, s1: stackFrame1, s2: stackFrame2, } : { s0: stackFrame0, s1: stackFrame1, }, sourceCode: createDebuggerSourceCodeState({ focusLineSpec: { host_name: 'localhost', file_path: 'main.py', lineno: 20, function_name: 'main', }, }), stickToBottommostFrameInFocusedFile, }); const nextState = reducers( state, actions.graphOpFocused({graph_id: 'g1', op_name: 'op2'}) ); expect(nextState.graphs.focusedOp).toEqual({ graphId: 'g1', opName: 'op2', }); expect(nextState.codeLocationFocusType).toBe( CodeLocationType.GRAPH_OP_CREATION ); expect(nextState.sourceCode.focusLineSpec).toEqual({ host_name: 'localhost', file_path: 'main.py', lineno: expectedLineno, function_name: expectedFunctionName, }); } ); } }); describe('graphExecutionFocused', () => { it('sets focusIndex, focusedOp & focus type from empty state', () => { const state = createDebuggerState(); const nextState = reducers( state, actions.graphExecutionFocused({ index: 42, graph_id: 'g2', op_name: 'TestOp_12', }) ); expect(nextState.graphExecutions.focusIndex).toBe(42); expect(nextState.graphs.focusedOp).toEqual({ graphId: 'g2', opName: 'TestOp_12', }); expect(nextState.codeLocationFocusType).toBe( CodeLocationType.GRAPH_OP_CREATION ); }); it('sets focusIndex, focusedOp & focus type from non-empty state', () => { const state = createDebuggerState({ graphExecutions: createDebuggerGraphExecutionsState({ focusIndex: 3, }), graphs: createDebuggerGraphsState({ focusedOp: { graphId: 'g1', opName: 'TestOp_1', }, }), }); const nextState = reducers( state, actions.graphExecutionFocused({ index: 42, graph_id: 'g2', op_name: 'TestOp_12', }) ); expect(nextState.graphExecutions.focusIndex).toBe(42); expect(nextState.graphs.focusedOp).toEqual({ graphId: 'g2', opName: 'TestOp_12', }); expect(nextState.codeLocationFocusType).toBe( CodeLocationType.GRAPH_OP_CREATION ); }); }); describe('graphOpInfoRequested', () => { it('creates key for new graph_id', () => { const state = createDebuggerState(); const nextState = reducers( state, actions.graphOpInfoRequested({graph_id: 'g8', op_name: 'x'}) ); expect(nextState.graphs.loadingOps).toEqual({ g8: new Map([['x', DataLoadState.LOADING]]), }); }); it('adds op to existing graph key', () => { const state = createDebuggerState({ graphs: createDebuggerGraphsState({ loadingOps: { g1: new Map([['Op1', DataLoadState.LOADING]]), g2: new Map([['Op2', DataLoadState.LOADING]]), }, }), }); const nextState = reducers( state, actions.graphOpInfoRequested({graph_id: 'g2', op_name: 'Op3'}) ); expect(nextState.graphs.loadingOps).toEqual({ g1: new Map([['Op1', DataLoadState.LOADING]]), g2: new Map([ ['Op2', DataLoadState.LOADING], ['Op3', DataLoadState.LOADING], ]), }); }); it('no effect for an already-loading op', () => { const state = createDebuggerState({ graphs: createDebuggerGraphsState({ loadingOps: { g1: new Map([['Op1', DataLoadState.LOADING]]), g2: new Map([['Op2', DataLoadState.LOADING]]), }, }), }); const nextState = reducers( state, actions.graphOpInfoRequested({graph_id: 'g2', op_name: 'Op2'}) ); expect(nextState.graphs.loadingOps).toEqual({ g1: new Map([['Op1', DataLoadState.LOADING]]), g2: new Map([['Op2', DataLoadState.LOADING]]), }); }); }); describe('graphOpInfoLoaded', () => { it('updates self op, 1 input op and 1 consumer op', () => { const opInfo0 = createTestGraphOpInfo(); const state = createDebuggerState({ graphs: createDebuggerGraphsState({ ops: { g0: new Map([[opInfo0.op_name, opInfo0]]), }, loadingOps: { g2: new Map([['TestOp_1', DataLoadState.LOADING]]), }, }), }); const opInfo1 = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); const opInfo2 = createTestGraphOpInfo({ op_name: 'TestOp_1', graph_ids: ['g1', 'g2'], }); opInfo1.consumers = [ [ { op_name: opInfo2.op_name, input_slot: 0, }, ], ]; opInfo2.inputs = [ { op_name: opInfo1.op_name, output_slot: 0, }, ]; const opInfo3 = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); opInfo2.consumers = [ [ { op_name: opInfo3.op_name, input_slot: 0, }, ], ]; opInfo3.inputs = [ { op_name: opInfo2.op_name, output_slot: 0, }, ]; const nextState = reducers( state, actions.graphOpInfoLoaded({ graphOpInfoResponse: { ...opInfo2, inputs: [ { ...opInfo2.inputs[0], data: opInfo1, }, ], consumers: [ [ { ...opInfo2.consumers[0][0], data: opInfo3, }, ], ], }, }) ); expect(nextState.graphs.ops).toEqual({ // Verify the old graph op data hasn't changed. g0: new Map([[opInfo0.op_name, opInfo0]]), // 'g2' is the immediately-enclosing graph of the three ops. g2: new Map([ [opInfo1.op_name, opInfo1], [opInfo2.op_name, opInfo2], [opInfo3.op_name, opInfo3], ]), }); // Verify that the input and consumer ops do not have the detailed data attached. expect( nextState.graphs.ops['g2'].get(opInfo2.op_name)!.inputs[0].data ).toBeUndefined(); expect( nextState.graphs.ops['g2'].get(opInfo2.op_name)!.consumers[0][0].data ).toBeUndefined(); expect(nextState.graphs.loadingOps).toEqual({ g2: new Map([['TestOp_1', DataLoadState.LOADED]]), }); }); it('updates self op, 2 input ops and 2 consumer ops', () => { const opInfo0 = createTestGraphOpInfo(); const state = createDebuggerState({ graphs: createDebuggerGraphsState({ ops: { // TODO(cais): Is typing necessary? g0: new Map([[opInfo0.op_name, opInfo0]]), }, loadingOps: { g1: new Map([['TestOp_11', DataLoadState.LOADING]]), g2: new Map([ ['TestOp_2', DataLoadState.LOADING], ['TestOp_22', DataLoadState.LOADING], ]), }, }), }); const opInfo1a = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); const opInfo1b = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); const opInfo2 = createTestGraphOpInfo({ op_name: 'TestOp_2', graph_ids: ['g1', 'g2'], }); opInfo1a.consumers = [ [ { op_name: opInfo2.op_name, input_slot: 0, }, ], ]; opInfo1b.consumers = [ [ { op_name: opInfo2.op_name, input_slot: 1, }, ], ]; opInfo2.inputs = [ { op_name: opInfo1a.op_name, output_slot: 0, }, { op_name: opInfo1b.op_name, output_slot: 0, }, ]; const opInfo3a = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); const opInfo3b = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); opInfo2.consumers = [ [ { op_name: opInfo3a.op_name, input_slot: 0, }, { op_name: opInfo3b.op_name, input_slot: 0, }, ], ]; opInfo3a.inputs = [ { op_name: opInfo2.op_name, output_slot: 0, }, ]; opInfo3b.inputs = [ { op_name: opInfo2.op_name, output_slot: 0, }, ]; const nextState = reducers( state, actions.graphOpInfoLoaded({ graphOpInfoResponse: { ...opInfo2, inputs: [ { ...opInfo2.inputs[0], data: opInfo1a, }, { ...opInfo2.inputs[1], data: opInfo1b, }, ], consumers: [ [ { ...opInfo2.consumers[0][0], data: opInfo3a, }, { ...opInfo2.consumers[0][1], data: opInfo3b, }, ], ], }, }) ); expect(nextState.graphs.ops).toEqual({ // Verify the old graph op data hasn't changed. g0: new Map([[opInfo0.op_name, opInfo0]]), // 'g2' is the immediately-enclosing graph of the three ops. g2: new Map([ [opInfo1a.op_name, opInfo1a], [opInfo1b.op_name, opInfo1b], [opInfo2.op_name, opInfo2], [opInfo3a.op_name, opInfo3a], [opInfo3b.op_name, opInfo3b], ]), }); expect(nextState.graphs.loadingOps).toEqual({ g1: new Map([['TestOp_11', DataLoadState.LOADING]]), g2: new Map([ ['TestOp_2', DataLoadState.LOADED], ['TestOp_22', DataLoadState.LOADING], ]), }); }); it('updates self op and input op: no consumer op', () => { const opInfo0 = createTestGraphOpInfo(); const state = createDebuggerState({ graphs: createDebuggerGraphsState({ ops: { // Pre-existing op in store. g0: new Map([[opInfo0.op_name, opInfo0]]), }, loadingOps: { g2: new Map([['TestOp_3', DataLoadState.LOADING]]), }, }), }); const opInfo1 = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); const opInfo2 = createTestGraphOpInfo({ op_name: 'TestOp_3', graph_ids: ['g1', 'g2'], }); opInfo1.consumers = [ [ { op_name: opInfo2.op_name, input_slot: 0, }, ], ]; opInfo2.inputs = [ { op_name: opInfo1.op_name, output_slot: 0, }, ]; opInfo2.consumers = []; // Has no consumers. const nextState = reducers( state, actions.graphOpInfoLoaded({ graphOpInfoResponse: { ...opInfo2, inputs: [ { ...opInfo2.inputs[0], data: opInfo1, }, ], }, }) ); expect(nextState.graphs.ops).toEqual({ g0: new Map([[opInfo0.op_name, opInfo0]]), g2: new Map([ [opInfo1.op_name, opInfo1], [opInfo2.op_name, opInfo2], ]), }); expect(nextState.graphs.loadingOps).toEqual({ g2: new Map([['TestOp_3', DataLoadState.LOADED]]), }); }); it('updates self op and consumer ops: no input ops', () => { const opInfo0 = createTestGraphOpInfo(); const state = createDebuggerState({ graphs: createDebuggerGraphsState({ ops: { // Pre-existing op in store. g0: new Map([[opInfo0.op_name, opInfo0]]), }, loadingOps: { g2: new Map([['TestOp_4', DataLoadState.LOADING]]), }, }), }); const opInfo1 = createTestGraphOpInfo({ op_name: 'TestOp_4', graph_ids: ['g1', 'g2'], }); opInfo1.inputs = []; // Has no inputs. const opInfo2 = createTestGraphOpInfo({ graph_ids: ['g1', 'g2'], }); opInfo1.consumers = [ [ { op_name: opInfo2.op_name, input_slot: 0, }, ], ]; opInfo2.inputs = [ { op_name: opInfo1.op_name, output_slot: 0, }, ]; const nextState = reducers( state, actions.graphOpInfoLoaded({ graphOpInfoResponse: { ...opInfo1, consumers: [ [ { ...opInfo1.consumers[0][0], data: opInfo2, }, ], ], }, }) ); expect(nextState.graphs.ops).toEqual({ g0: new Map([[opInfo0.op_name, opInfo0]]), g2: new Map([ [opInfo1.op_name, opInfo1], [opInfo2.op_name, opInfo2], ]), }); expect(nextState.graphs.loadingOps).toEqual({ g2: new Map([['TestOp_4', DataLoadState.LOADED]]), }); }); }); });
the_stack
import { Component, Input, Optional, Inject, OnChanges, ViewChildren, EventEmitter, Output, ChangeDetectorRef, QueryList, AfterViewInit, ViewChild, ElementRef, OnDestroy, AfterContentInit, TemplateRef, Self, } from '@angular/core'; import { NgControl } from '@angular/forms'; import { ConnectedOverlayPositionChange } from '@angular/cdk/overlay'; import { ActiveDescendantKeyManager } from '@angular/cdk/a11y'; import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; import { I18nService } from '../i18n/i18n.service'; import { AUTOCOMPLETE_CONFIG, AutoCompleteConfig } from './interfaces/autocomplete.config'; import { DataSourceList } from '../core/classes/datasource-list'; import { TlItemSelectedDirective } from '../core/directives/itemSelected/item-selected.directive'; import { scrollIntoView } from '../core/helper/scrollIntoView'; import { SelectedItemService } from './services/selected-item.service'; import { Subscription } from 'rxjs'; import * as objectPath from 'object-path'; import { ValueAccessorBase } from '../input/core/value-accessor'; import { TlInput } from '../input/input'; @Component( { selector: 'tl-autocomplete', templateUrl: './autocomplete.html', styleUrls: [ './autocomplete.scss' ], providers: [ SelectedItemService ], } ) export class TlAutoComplete extends ValueAccessorBase<any> implements OnChanges, OnDestroy, AfterViewInit, AfterContentInit { @Input( 'data' ) set data( value ) { this._data = value; } get data() { return this._data; } @Input('control') set control(item) { this._control = item; } @Input() totalLength = 1000; @Input() filterOperator = '%'; @Input() rowsPage = 100; @Input() lazyMode = false; @Input() rowHeight = 40; @Input() template: TemplateRef<any>; @Input() debounceTime = 200; @Input() keyText = ''; @Input() keyValue = null; @Input() openFocus = true; @Input() chainFilter = false; @Input() loading = false; @Input() clearButton = true; @Input() clearOnSelect = false; @Input() disabled: boolean = null; @Input() required: boolean = null; @Input() color = 'basic'; @Input() labelPlacement: 'top' | 'left' = 'left'; @Input() textBefore = null; @Input() textAfter = null; @Input() iconBefore = null; @Input() iconAfter = null; @Input() labelSize = '100px'; @Input() height = '23px'; @Input() containerHeight = '200px'; @Input() searchBy = ''; @Input() label = ''; @Input() identifier = null; @Input() placeholder = 'Search...'; @Input() modelMode: 'string' | 'object' = 'object'; @Output() lazyLoad: EventEmitter<any> = new EventEmitter(); @Output() selectItem: EventEmitter<any> = new EventEmitter(); @Output() changeSelected: EventEmitter<any> = new EventEmitter(); @Output() filter: EventEmitter<any> = new EventEmitter(); @Output() clickAddon: EventEmitter<any> = new EventEmitter(); @ViewChild( 'input', {static: true} ) input: ElementRef; @ViewChild( CdkVirtualScrollViewport, {static: false} ) cdkVirtualScroll: CdkVirtualScrollViewport; @ViewChildren( TlItemSelectedDirective ) listItems: QueryList<TlItemSelectedDirective>; @ViewChild( TlInput, {static: true} ) tlinput: TlInput; public keyManager: ActiveDescendantKeyManager<TlItemSelectedDirective>; public dataSource: DataSourceList; public isOpen = false; public focused = false; public selected; public description = ''; public trigger; public positionOverlay: 'top' | 'bottom' | 'center'; public nothingFound = false; public tempContainerHeight; public messageLoading = this.i18n.getLocale().AutoComplete.messageLoading; public nothingFoundMessage = this.i18n.getLocale().AutoComplete.nothingFoundMessage; private filtering = false; private modelInitialized = false; private lastItemScrolled = 0; private subscription: Subscription = new Subscription(); private _data = []; private _control; constructor( @Optional() @Inject( AUTOCOMPLETE_CONFIG ) autoCompleteConfig: AutoCompleteConfig, private change: ChangeDetectorRef, private i18n: I18nService, private itemSelectedService: SelectedItemService, @Optional() @Self() public ngControl: NgControl ) { super(); this.setControl(); this.setOptions( autoCompleteConfig ); } get control() { return this.ngControl?.control; } setControl() { if ( this.ngControl ) { this.ngControl.valueAccessor = this; } } ngAfterContentInit() { this.handleModelLazy(); this.handleModelCached(); this.listenModelChanges(); this.change.markForCheck(); } ngAfterViewInit() { this.keyManager = new ActiveDescendantKeyManager( this.listItems ); this.tempContainerHeight = this.containerHeight; this.validateKeyValue(); } getNativeInput() { return this.tlinput.getNativeInput(); } private validateKeyValue() { if ( !this.isModelModeString() && !this.keyValue && !this.identifier ) { throw Error( 'The AutoComplete should have an [identifier] key property, ' + ' because the property [keyValue] is null and the list is working on [modelMode] \'object\'' ); } } private listenModelChanges() { if ( this.control ) { this.control.valueChanges.subscribe( ( value ) => { if ( this.dataSource ) { this.handleModelLazy(); this.handleModelCached(); } } ); } } private handleItemSelected() { if ( this.itemSelectedService.itemSelected ) { this.scrollToIndex().then( value => { this.keyManager.setActiveItem( this.itemSelectedService.itemSelected.indexSelected ); } ); } } private scrollToIndex() { return new Promise( ( resolve ) => { setTimeout( () => { if ( this.cdkVirtualScroll ) { this.cdkVirtualScroll.scrollToIndex( this.lastItemScrolled ); this.change.markForCheck(); } resolve(); }, 200 ); } ); } onScrollIndexChange( $event ) { if ( $event > 0 ) { this.lastItemScrolled = $event; } } onInput() { this.setIsOpen( true ); this.setFiltering( true ); } close() { if ( !this.control.disabled ) { this.value = null; this.setDescriptionValue( '' ); this.selected = null; } } onBackdropClick() { this.setIsOpen( false ); this.setFiltering( false ); } private handleModelLazy() { if (this.value && this.lazyMode) { const value = objectPath.get(this.value, this.keyText); if ( value ) { this.setDescriptionValue(value); this.handleKeyModelValue(this.value); this.changeSelected.emit(this.value); } } } private setDescriptionValue( value: string ) { this.description = value; } private handleModelCached() { if ( this.dataSource && !this.lazyMode && this.data.length > 0 ) { this.data.forEach( ( value ) => { if ( this.value ) { if ( String( this.getItemCompare( value ) ) === String( this.getCompareModel() ) ) { this.setDescriptionValue( objectPath.get( value, this.keyText ) ); this.handleKeyModelValue( value ); this.changeSelected.emit( value ); } } } ); } } private getItemCompare( value ) { if ( !this.keyValue || this.isModelModeString() ) { return objectPath.get( value, this.identifier ); } return objectPath.get( value, this.keyValue ); } private handleKeyModelValue( value ) { this.modelInitialized = true; this.selected = value; if ( !this.isModelModeString() && this.keyValue ) { this.value = objectPath.get( value, this.keyValue ); return; } if ( this.isModelModeString() && !this.keyValue ) { this.value = objectPath.get( value, this.identifier ); return; } if ( this.isModelModeString() && this.keyValue ) { this.value = objectPath.get( value, this.keyValue ); return; } this.value = value; } private setOptions( options: AutoCompleteConfig ) { if ( options ) { const self = this; Object.keys( options ).forEach( function ( key ) { self[ key ] = options[ key ]; } ); } } private setSelected( itemDirective: TlItemSelectedDirective ) { this.selected = itemDirective.itemSelected; this.keyManager.setActiveItem( itemDirective ); this.itemSelectedService.itemSelected = itemDirective; } stopEvent( $event ) { $event.preventDefault(); $event.stopPropagation(); } handleKeyArrowDown( $event ) { if ( this.loading ) { this.stopEvent($event); return; } this.handleEventOpenList( $event ); if ( !this.keyManager.activeItem ) { this.keyManager.setFirstItemActive(); return; } this.keyManager.onKeydown( $event ); scrollIntoView( this.keyManager.activeItem.element.nativeElement ); } handleKeyArrowUp( $event ) { this.handleEventOpenList( $event ); if ( !this.keyManager.activeItem ) { this.keyManager.setFirstItemActive(); return; } this.keyManager.onKeydown( $event ); scrollIntoView( this.keyManager.activeItem.element.nativeElement ); } handleKeyBackspace() { this.value = null; } handleEventOpenList( $event ) { if ( this.isOpen ) { this.stopEvent( $event ); } } handleKeyEscape( $event ) { if ( this.isOpen ) { $event.stopPropagation(); } this.setIsOpen( false ); } handleKeyEnter($event) { if ( this.keyManager.activeItem && this.isOpen ) { if ( this.keyManager.activeItem.itemSelected ) { this.selectItem.emit( this.keyManager.activeItem.itemSelected ); this.setSelected( <TlItemSelectedDirective>this.keyManager.activeItem ); this.setDescriptionValue( objectPath.get( this.keyManager.activeItem.itemSelected, this.keyText ) ); this.handleKeyModelValue( this.keyManager.activeItem.itemSelected ); } this.handleClose($event); } } handleFocus() { this.focused = true; if ( this.openFocus && !this.keyManager.activeItem && !this.isDisabled && !this.disabled ) { if ( this.openFocus ) { this.setIsOpen( true ); } } } private isModelModeString() { return this.modelMode === 'string'; } private getCompareModel() { if ( this.keyValue && !this.isModelModeString() ) { return objectPath.get( this.value, this.keyValue ); } if ( !this.isModelModeString() && !this.keyValue ) { return objectPath.get( this.value, this.identifier ); } return this.value; } onSelectItem( value: any, item: TlItemSelectedDirective ) { this.setDescriptionValue( objectPath.get( value, this.keyText ) ); this.handleKeyModelValue( value ); this.setSelected( item ); this.selectItem.emit( value ); this.handleClose(); this.change.detectChanges(); } handleClose($event?) { if ( this.clearOnSelect ) { this.setDescriptionValue( '' ); this.tlinput.setFocus(); this.selected = null; if ( $event ) { $event.stopPropagation(); } } this.setIsOpen( false ); } private setUpData( value? ) { if ( !this.dataSource ) { this.dataSource = new DataSourceList( { dataSource: value, pageSize: this.rowsPage, totalLength: this.totalLength, lazyMode: this.lazyMode } ); this.listenLoadData(); this.handleModelCached(); } this.dataSource.setData( value ); this.loading = false; // this.setContainerHeight( value ); this.setNotFound( value.length === 0 ); this.setFirstItemActive(); } setContainerHeight( data ) { if ( this.filtering ) { const currentHeight = parseInt(this.containerHeight, 10); const maxContent = Math.round(currentHeight / this.rowHeight); if ( data.length === 0 ) { this.tempContainerHeight = this.rowHeight + 'px'; } else if ( data.length <= maxContent ) { this.tempContainerHeight = (data.length * this.rowHeight) + 'px'; } else { this.tempContainerHeight = this.containerHeight; } this.change.detectChanges(); } } private setFirstItemActive() { if ( this.keyManager ) { setTimeout( () => { this.keyManager.setFirstItemActive(); }, 100 ); } } private listenLoadData() { this.subscription.add( this.dataSource.loadMoreData.subscribe( ( data: any ) => { this.lazyLoad.emit( { skip: data.skip, limit: data.limit, ...this.getFilters( this.description ) } ); this.loading = true; } ) ); } onPositionChange( $event: ConnectedOverlayPositionChange ) { this.positionOverlay = $event.connectionPair.originY; this.change.detectChanges(); } private setIsOpen( value: boolean ) { this.isOpen = value; } getItemText( item ) { return objectPath.get( item, this.keyText ); } toggleIsOpen() { if ( !this.disabled && !this.isDisabled ) { this.isOpen = !this.isOpen; this.tlinput.setFocus(); this.handleItemSelected(); } } private getFilters( term: string ) { const fields = {}; fields[ this.searchBy ] = !this.chainFilter ? { matchMode: 'contains', value: term } : term.split(this.filterOperator).map(( value ) => { return { matchMode: 'contains', value: value }; }); return { fields: fields, operator: 'or' }; } private setScrollVirtual() { if ( this.cdkVirtualScroll ) { this.cdkVirtualScroll.elementRef.nativeElement.scrollTop = 0; } } onFilter( $event ) { this.setScrollVirtual(); this.setFiltering( true ); this.dataSource.resetPages(); if ( this.lazyMode ) { this.filter.emit( this.getFilters( $event ) ); return; } if ( $event ) { this.dataSource.setArray( $event.length ); this.setUpData( $event ); return; } this.dataSource.setData( [] ); this.setNotFound( true ); this.selected = null; } private setFiltering( value: boolean ) { this.filtering = value; } private setNotFound( value: boolean ) { this.nothingFound = value; } ngOnChanges( { data, totalLength }: any ) { if ( totalLength && !totalLength[ 'firstChange' ] ) { if ( this.dataSource ) { this.dataSource.setArray( totalLength[ 'currentValue' ] ); } } if ( data && this.lazyMode ) { this.setUpData( data[ 'currentValue' ] ); return; } if ( data && data[ 'currentValue' ] !== undefined && !this.lazyMode ) { if ( data[ 'currentValue' ].length > 0 ) { this.setUpData( data[ 'currentValue' ] ); } } } ngOnDestroy() { this.subscription.unsubscribe(); if ( this.dataSource ) { this.dataSource.unsubscribe(); } } }
the_stack
import { Angle, Point, Line, Rectangle, Polyline } from '../../geometry' import { createSvgElement } from './elem' const svgDocument = createSvgElement('svg') as SVGSVGElement const transformRegex = /(\w+)\(([^,)]+),?([^)]+)?\)/gi const transformSeparatorRegex = /[ ,]+/ const transformationListRegex = /^(\w+)\((.*)\)/ export interface MatrixLike { a: number b: number c: number d: number e: number f: number } export interface Translation { tx: number ty: number } export interface Rotation { angle: number cx?: number cy?: number } export interface Scale { sx: number sy: number } /** * Returns a SVG point object initialized with the `x` and `y` coordinates. * @see https://developer.mozilla.org/en/docs/Web/API/SVGPoint */ export function createSVGPoint(x: number, y: number) { const p = svgDocument.createSVGPoint() p.x = x p.y = y return p } /** * Returns the SVG transformation matrix initialized with the given matrix. * * The given matrix is an object of the form: * { * a: number * b: number * c: number * d: number * e: number * f: number * } * * @see https://developer.mozilla.org/en/docs/Web/API/SVGMatrix */ export function createSVGMatrix(matrix?: DOMMatrix | MatrixLike | null) { const mat = svgDocument.createSVGMatrix() if (matrix != null) { const source = matrix as any const target = mat as any // eslint-disable-next-line for (const key in source) { target[key] = source[key] } } return mat } /** * Returns a SVG transform object. * @see https://developer.mozilla.org/en/docs/Web/API/SVGTransform */ export function createSVGTransform(matrix?: DOMMatrix | MatrixLike) { if (matrix != null) { if (!(matrix instanceof DOMMatrix)) { matrix = createSVGMatrix(matrix) // eslint-disable-line } return svgDocument.createSVGTransformFromMatrix(matrix as DOMMatrix) } return svgDocument.createSVGTransform() } /** * Returns the SVG transformation matrix built from the `transformString`. * * E.g. 'translate(10,10) scale(2,2)' will result in matrix: * `{ a: 2, b: 0, c: 0, d: 2, e: 10, f: 10}` */ export function transformStringToMatrix(transform?: string | null) { let mat = createSVGMatrix() const matches = transform != null && transform.match(transformRegex) if (!matches) { return mat } for (let i = 0, n = matches.length; i < n; i += 1) { const transformationString = matches[i] const transformationMatch = transformationString.match( transformationListRegex, ) if (transformationMatch) { let sx let sy let tx let ty let angle let ctm = createSVGMatrix() const args = transformationMatch[2].split(transformSeparatorRegex) switch (transformationMatch[1].toLowerCase()) { case 'scale': sx = parseFloat(args[0]) sy = args[1] === undefined ? sx : parseFloat(args[1]) ctm = ctm.scaleNonUniform(sx, sy) break case 'translate': tx = parseFloat(args[0]) ty = parseFloat(args[1]) ctm = ctm.translate(tx, ty) break case 'rotate': angle = parseFloat(args[0]) tx = parseFloat(args[1]) || 0 ty = parseFloat(args[2]) || 0 if (tx !== 0 || ty !== 0) { ctm = ctm.translate(tx, ty).rotate(angle).translate(-tx, -ty) } else { ctm = ctm.rotate(angle) } break case 'skewx': angle = parseFloat(args[0]) ctm = ctm.skewX(angle) break case 'skewy': angle = parseFloat(args[0]) ctm = ctm.skewY(angle) break case 'matrix': ctm.a = parseFloat(args[0]) ctm.b = parseFloat(args[1]) ctm.c = parseFloat(args[2]) ctm.d = parseFloat(args[3]) ctm.e = parseFloat(args[4]) ctm.f = parseFloat(args[5]) break default: continue } mat = mat.multiply(ctm) } } return mat } export function matrixToTransformString( matrix?: DOMMatrix | Partial<MatrixLike>, ) { const m = matrix || ({} as DOMMatrix) const a = m.a != null ? m.a : 1 const b = m.b != null ? m.b : 0 const c = m.c != null ? m.c : 0 const d = m.d != null ? m.d : 1 const e = m.e != null ? m.e : 0 const f = m.f != null ? m.f : 0 return `matrix(${a},${b},${c},${d},${e},${f})` } export function parseTransformString(transform: string) { let translation let rotation let scale if (transform) { const separator = transformSeparatorRegex // Allow reading transform string with a single matrix if (transform.trim().indexOf('matrix') >= 0) { const matrix = transformStringToMatrix(transform) const decomposedMatrix = decomposeMatrix(matrix) translation = [decomposedMatrix.translateX, decomposedMatrix.translateY] rotation = [decomposedMatrix.rotation] scale = [decomposedMatrix.scaleX, decomposedMatrix.scaleY] const transformations = [] if (translation[0] !== 0 || translation[1] !== 0) { transformations.push(`translate(${translation.join(',')})`) } if (scale[0] !== 1 || scale[1] !== 1) { transformations.push(`scale(${scale.join(',')})`) } if (rotation[0] !== 0) { transformations.push(`rotate(${rotation[0]})`) } transform = transformations.join(' ') // eslint-disable-line } else { const translateMatch = transform.match(/translate\((.*?)\)/) if (translateMatch) { translation = translateMatch[1].split(separator) } const rotateMatch = transform.match(/rotate\((.*?)\)/) if (rotateMatch) { rotation = rotateMatch[1].split(separator) } const scaleMatch = transform.match(/scale\((.*?)\)/) if (scaleMatch) { scale = scaleMatch[1].split(separator) } } } const sx = scale && scale[0] ? parseFloat(scale[0] as string) : 1 return { raw: transform || '', translation: { tx: translation && translation[0] ? parseInt(translation[0] as string, 10) : 0, ty: translation && translation[1] ? parseInt(translation[1] as string, 10) : 0, } as Translation, rotation: { angle: rotation && rotation[0] ? parseInt(rotation[0] as string, 10) : 0, cx: rotation && rotation[1] ? parseInt(rotation[1] as string, 10) : undefined, cy: rotation && rotation[2] ? parseInt(rotation[2] as string, 10) : undefined, } as Rotation, scale: { sx, sy: scale && scale[1] ? parseFloat(scale[1] as string) : sx, } as Scale, } } function deltaTransformPoint( matrix: DOMMatrix | MatrixLike, point: Point | Point.PointLike, ) { const dx = point.x * matrix.a + point.y * matrix.c + 0 const dy = point.x * matrix.b + point.y * matrix.d + 0 return { x: dx, y: dy } } /** * Decomposes the SVG transformation matrix into separate transformations. * * Returns an object of the form: * { * translateX: number * translateY: number * scaleX: number * scaleY: number * skewX: number * skewY: number * rotation: number * } * * @see https://developer.mozilla.org/en/docs/Web/API/SVGMatrix */ export function decomposeMatrix(matrix: DOMMatrix | MatrixLike) { // @see https://gist.github.com/2052247 const px = deltaTransformPoint(matrix, { x: 0, y: 1 }) const py = deltaTransformPoint(matrix, { x: 1, y: 0 }) const skewX = (180 / Math.PI) * Math.atan2(px.y, px.x) - 90 const skewY = (180 / Math.PI) * Math.atan2(py.y, py.x) return { skewX, skewY, translateX: matrix.e, translateY: matrix.f, scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b), scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d), rotation: skewX, } } export function matrixToScale(matrix: DOMMatrix | MatrixLike): Scale { let a let b let c let d if (matrix) { a = matrix.a == null ? 1 : matrix.a d = matrix.d == null ? 1 : matrix.d b = matrix.b c = matrix.c } else { a = d = 1 } return { sx: b ? Math.sqrt(a * a + b * b) : a, sy: c ? Math.sqrt(c * c + d * d) : d, } } export function matrixToRotation(matrix: DOMMatrix | MatrixLike): Rotation { let p = { x: 0, y: 1 } if (matrix) { p = deltaTransformPoint(matrix, p) } return { angle: Angle.normalize(Angle.toDeg(Math.atan2(p.y, p.x)) - 90), } } export function matrixToTranslation( matrix: DOMMatrix | MatrixLike, ): Translation { return { tx: (matrix && matrix.e) || 0, ty: (matrix && matrix.f) || 0, } } /** * Transforms point by an SVG transformation represented by `matrix`. */ export function transformPoint(point: Point.PointLike, matrix: DOMMatrix) { const ret = createSVGPoint(point.x, point.y).matrixTransform(matrix) return new Point(ret.x, ret.y) } /** * Transforms line by an SVG transformation represented by `matrix`. */ export function transformLine(line: Line, matrix: DOMMatrix) { return new Line( transformPoint(line.start, matrix), transformPoint(line.end, matrix), ) } /** * Transforms polyline by an SVG transformation represented by `matrix`. */ export function transformPolyline(polyline: Polyline, matrix: DOMMatrix) { let points = polyline instanceof Polyline ? polyline.points : polyline if (!Array.isArray(points)) { points = [] } return new Polyline(points.map((p) => transformPoint(p, matrix))) } export function transformRectangle( rect: Rectangle.RectangleLike, matrix: DOMMatrix, ) { const p = svgDocument.createSVGPoint() p.x = rect.x p.y = rect.y const corner1 = p.matrixTransform(matrix) p.x = rect.x + rect.width p.y = rect.y const corner2 = p.matrixTransform(matrix) p.x = rect.x + rect.width p.y = rect.y + rect.height const corner3 = p.matrixTransform(matrix) p.x = rect.x p.y = rect.y + rect.height const corner4 = p.matrixTransform(matrix) const minX = Math.min(corner1.x, corner2.x, corner3.x, corner4.x) const maxX = Math.max(corner1.x, corner2.x, corner3.x, corner4.x) const minY = Math.min(corner1.y, corner2.y, corner3.y, corner4.y) const maxY = Math.max(corner1.y, corner2.y, corner3.y, corner4.y) return new Rectangle(minX, minY, maxX - minX, maxY - minY) }
the_stack
import * as Yup from 'yup' import { IRuleFunction, IRule, IRuleOptions, ICache, IFragment, ICacheContructorOptions, IRuleConstructorOptions, ILogicRule, ShieldRule, IRuleResult, IOptions, IShieldContext, } from './types' import { isLogicRule } from './utils' import { GraphQLResolveInfo } from 'graphql' import { isUndefined } from 'util' export class Rule implements IRule { readonly name: string private cache: ICache private fragment?: IFragment private func: IRuleFunction constructor( name: string, func: IRuleFunction, constructorOptions: IRuleConstructorOptions, ) { const options = this.normalizeOptions(constructorOptions) this.name = name this.func = func this.cache = options.cache this.fragment = options.fragment } /** * * @param parent * @param args * @param ctx * @param info * * Resolves rule and writes to cache its result. * */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { try { /* Resolve */ const res = await this.executeRule(parent, args, ctx, info, options) if (res instanceof Error) { return res } else if (typeof res === 'string') { return new Error(res) } else if (res === true) { return true } else { return false } } catch (err) { if (options.debug) { throw err } else { return false } } } /** * * @param rule * * Compares a given rule with the current one * and checks whether their functions are equal. * */ equals(rule: Rule): boolean { return this.func === rule.func } /** * * Extracts fragment from the rule. * */ extractFragment(): IFragment | undefined { return this.fragment } /** * * @param options * * Sets default values for options. * */ private normalizeOptions(options: IRuleConstructorOptions): IRuleOptions { return { cache: options.cache !== undefined ? this.normalizeCacheOption(options.cache) : 'no_cache', fragment: options.fragment !== undefined ? options.fragment : undefined, } } /** * * @param cache * * This ensures backward capability of shield. * */ private normalizeCacheOption(cache: ICacheContructorOptions): ICache { switch (cache) { case true: { return 'strict' } case false: { return 'no_cache' } default: { return cache } } } /** * Executes a rule and writes to cache if needed. * * @param parent * @param args * @param ctx * @param info */ private executeRule( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): string | boolean | Error | Promise<IRuleResult> { switch (typeof this.cache) { case 'function': { /* User defined cache function. */ const key = `${this.name}-${this.cache(parent, args, ctx, info)}` return this.writeToCache(key)(parent, args, ctx, info) } case 'string': { /* Standard cache option. */ switch (this.cache) { case 'strict': { const key = options.hashFunction({ parent, args }) return this.writeToCache(`${this.name}-${key}`)( parent, args, ctx, info, ) } case 'contextual': { return this.writeToCache(this.name)(parent, args, ctx, info) } case 'no_cache': { return this.func(parent, args, ctx, info) } } } /* istanbul ignore next */ default: { throw new Error(`Unsupported cache format: ${typeof this.cache}`) } } } /** * Writes or reads result from cache. * * @param key */ private writeToCache( key: string, ): ( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, ) => string | boolean | Error | Promise<IRuleResult> { return (parent, args, ctx, info) => { if (!ctx._shield.cache[key]) { ctx._shield.cache[key] = this.func(parent, args, ctx, info) } return ctx._shield.cache[key] } } } export class InputRule<T> extends Rule { constructor( name: string, schema: (yup: typeof Yup, ctx: IShieldContext) => Yup.Schema<T>, options?: Yup.ValidateOptions, ) { const validationFunction: IRuleFunction = ( parent: object, args: object, ctx: IShieldContext, ) => schema(Yup, ctx) .validate(args, options) .then(() => true) .catch((err) => err) super(name, validationFunction, { cache: 'strict', fragment: undefined }) } } export class LogicRule implements ILogicRule { private rules: ShieldRule[] constructor(rules: ShieldRule[]) { this.rules = rules } /** * By default logic rule resolves to false. */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { return false } /** * Evaluates all the rules. */ async evaluate( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult[]> { const rules = this.getRules() const tasks = rules.map((rule) => rule.resolve(parent, args, ctx, info, options), ) return Promise.all(tasks) } /** * Returns rules in a logic rule. */ getRules() { return this.rules } /** * Extracts fragments from the defined rules. */ extractFragments(): IFragment[] { const fragments = this.rules.reduce<IFragment[]>((fragments, rule) => { if (isLogicRule(rule)) { return fragments.concat(...rule.extractFragments()) } const fragment = rule.extractFragment() if (fragment) return fragments.concat(fragment) return fragments }, []) return fragments } } // Extended Types export class RuleOr extends LogicRule { constructor(rules: ShieldRule[]) { super(rules) } /** * Makes sure that at least one of them has evaluated to true. */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { const result = await this.evaluate(parent, args, ctx, info, options) if (result.every((res) => res !== true)) { const customError = result.find((res) => res instanceof Error) return customError || false } else { return true } } } export class RuleAnd extends LogicRule { constructor(rules: ShieldRule[]) { super(rules) } /** * Makes sure that all of them have resolved to true. */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { const result = await this.evaluate(parent, args, ctx, info, options) if (result.some((res) => res !== true)) { const customError = result.find((res) => res instanceof Error) return customError || false } else { return true } } } export class RuleChain extends LogicRule { constructor(rules: ShieldRule[]) { super(rules) } /** * Makes sure that all of them have resolved to true. */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { const result = await this.evaluate(parent, args, ctx, info, options) if (result.some((res) => res !== true)) { const customError = result.find((res) => res instanceof Error) return customError || false } else { return true } } /** * Evaluates all the rules. */ async evaluate( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult[]> { const rules = this.getRules() return iterate(rules) async function iterate([rule, ...otherRules]: ShieldRule[]): Promise< IRuleResult[] > { if (isUndefined(rule)) return [] return rule.resolve(parent, args, ctx, info, options).then((res) => { if (res !== true) { return [res] } else { return iterate(otherRules).then((ress) => ress.concat(res)) } }) } } } export class RuleRace extends LogicRule { constructor(rules: ShieldRule[]) { super(rules) } /** * Makes sure that at least one of them resolved to true. */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { const result = await this.evaluate(parent, args, ctx, info, options) if (result.some((res) => res === true)) { return true } else { const customError = result.find((res) => res instanceof Error) return customError || false } } /** * Evaluates all the rules. */ async evaluate( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult[]> { const rules = this.getRules() return iterate(rules) async function iterate([rule, ...otherRules]: ShieldRule[]): Promise< IRuleResult[] > { if (isUndefined(rule)) return [] return rule.resolve(parent, args, ctx, info, options).then((res) => { if (res === true) { return [res] } else { return iterate(otherRules).then((ress) => ress.concat(res)) } }) } } } export class RuleNot extends LogicRule { error?: Error constructor(rule: ShieldRule, error?: Error) { super([rule]) this.error = error } /** * * @param parent * @param args * @param ctx * @param info * * Negates the result. * */ async resolve( parent: object, args: object, ctx: IShieldContext, info: GraphQLResolveInfo, options: IOptions, ): Promise<IRuleResult> { const [res] = await this.evaluate(parent, args, ctx, info, options) if (res instanceof Error) { return true } else if (res !== true) { return true } else { if (this.error) return this.error return false } } } export class RuleTrue extends LogicRule { constructor() { super([]) } /** * * Always true. * */ async resolve(): Promise<IRuleResult> { return true } } export class RuleFalse extends LogicRule { constructor() { super([]) } /** * * Always false. * */ async resolve(): Promise<IRuleResult> { return false } }
the_stack
import React, { useCallback, useEffect, useRef, useState } from 'react'; import { Image, Text, TextInput, StyleSheet, ScrollView, View, TouchableOpacity, Alert, LayoutChangeEvent, } from 'react-native'; import { useDispatch, useSelector } from '@/store'; import { useTranslation } from 'react-i18next'; import { useActionSheet } from '@expo/react-native-action-sheet'; import { DEVICE_LARGE, DEVICE_IOS, WIDTH } from '@/utils/deviceConstants'; import { DARK_ORANGE, LIGHT_GREY, DARKER_GREY, WHITE, BLACK, GREEN, DARK_BLUE, BLUE, } from '@/theme/colors'; import { fontSize } from '@/theme/fonts'; import { useFocusEffect, useNavigation } from '@react-navigation/native'; import { useHeaderHeight } from '@react-navigation/stack'; import { useIsDrawerOpen } from '@react-navigation/drawer'; import { chooseImage, takePhoto } from '@/utils/images'; import { saveImage, retrieveImage, photoDirectory } from '@/utils/filesystem'; import { setPhoto, setName } from '@/actions'; import Chevron from '@/components/Icons/Chevron'; import Material from 'react-native-vector-icons/MaterialCommunityIcons'; import { selectAllSocialMedia, removeSocialMedia, setProfileDisplayWidth, } from './socialMediaSlice'; const EditProfilePhoto = ({ profilePhoto, setProfilePhoto }) => { const { showActionSheetWithOptions } = useActionSheet(); const prevPhotoFilename = useSelector( (state: State) => state.user.photo.filename, ); const { t } = useTranslation(); const profileSource = profilePhoto ? { uri: profilePhoto, } : { uri: `file://${photoDirectory()}/${prevPhotoFilename}`, }; const getPhotoFromCamera = async () => { try { const { mime, data } = await takePhoto(); const uri = `data:${mime};base64,${data}`; setProfilePhoto(uri); } catch (err) { console.log(err); } }; const getPhotoFromLibrary = async () => { try { const { mime, data } = await chooseImage(); const uri = `data:${mime};base64,${data}`; setProfilePhoto(uri); } catch (err) { console.log(err); } }; const handleEditPhoto = () => { showActionSheetWithOptions( { options: [ t('common.photoActionSheet.takePhoto'), t('common.photoActionSheet.choosePhoto'), t('common.actionSheet.cancel'), ], cancelButtonIndex: 2, title: t('common.photoActionSheet.title'), showSeparators: true, textStyle: { color: BLUE, textAlign: 'center', width: '100%', fontSize: fontSize[18], }, titleTextStyle: { textAlign: 'center', fontSize: fontSize[20], width: '100%', }, }, (buttonIndex) => { if (buttonIndex === 0) { getPhotoFromCamera(); } else if (buttonIndex === 1) { getPhotoFromLibrary(); } }, ); }; return ( <View style={styles.profilePhotoContainer}> <TouchableOpacity testID="editPhoto" onPress={handleEditPhoto} accessible={true} accessibilityLabel={t('common.accessibilityLabel.editPhoto')} style={styles.changePhotoButton} > <Image source={profileSource} style={styles.photo} resizeMode="cover" onError={(e) => { console.log(e); }} accessible={true} accessibilityLabel="profile photo" /> <Text style={styles.profilePhotoText}> {t('profile.text.changeProfilePicture')} </Text> </TouchableOpacity> </View> ); }; const EditName = ({ nextName, setNextName }) => { const { t } = useTranslation(); return ( <View style={styles.editNameContainer}> <Text style={styles.label}>{t('profile.label.name')}</Text> <TextInput style={styles.editNameInput} value={nextName} onChangeText={setNextName} textContentType="name" placeholder={t('profile.placeholder.name')} placeholderTextColor={DARKER_GREY} /> </View> ); }; const SocialMediaLink = (props: SocialMedia) => { const navigation = useNavigation(); const dispatch = useDispatch(); const { id, profile, profileDisplayWidth, order, company } = props; // perfectly center profile text with max length const updateInnerTextLayout = (e: LayoutChangeEvent) => { if (!profileDisplayWidth) { if (e.nativeEvent?.layout?.width) { dispatch( setProfileDisplayWidth({ id, width: e.nativeEvent.layout.width, }), ); } else { dispatch( setProfileDisplayWidth({ id, width: '50%', }), ); } } }; const innerTextStyle = profileDisplayWidth ? { width: profileDisplayWidth } : { flexGrow: 1 }; return ( <View style={styles.socialMediaLinkContainer}> <TouchableOpacity style={styles.socialMediaSelect} onPress={() => { navigation.navigate('SelectSocialMedia', { order, prevId: id, page: 0, }); }} > <Text style={styles.socialMediaType}>{company.name}</Text> <Chevron width={DEVICE_LARGE ? 14 : 12} height={DEVICE_LARGE ? 14 : 12} color={DARK_BLUE} strokeWidth={2} /> </TouchableOpacity> <TouchableOpacity style={innerTextStyle} onLayout={updateInnerTextLayout} onPress={() => { navigation.navigate('SelectSocialMedia', { order, prevId: id, page: 1, }); }} > <Text style={styles.socialMediaInput} numberOfLines={1} ellipsizeMode="head" > {innerTextStyle.width ? profile : ''} </Text> </TouchableOpacity> <TouchableOpacity style={styles.closeButton} onPress={() => { dispatch(removeSocialMedia(id)); }} > <Material name="close" size={DEVICE_LARGE ? 18 : 16} color="#000" /> </TouchableOpacity> </View> ); }; const SocialMediaLinks = () => { const navigation = useNavigation(); const socialMediaItems = useSelector(selectAllSocialMedia); const { t } = useTranslation(); console.log('socialMedia', socialMediaItems); const SocialMediaList = socialMediaItems.map((item) => ( <SocialMediaLink key={item.id} {...item} /> )); return ( <View style={styles.socialMediaContainer}> <View style={styles.socialMediaLinkLabel}> <Text style={styles.label}>{t('profile.label.socialMediaLink')}</Text> <TouchableOpacity onPress={() => { navigation.navigate('SelectSocialMedia', { order: socialMediaItems.length, prevId: null, page: 0, }); }} style={styles.addSocialMediaBtn} > <Material name="plus-thick" size={DEVICE_LARGE ? 18 : 16} color={DARK_BLUE} /> </TouchableOpacity> </View> {SocialMediaList} <View style={styles.bottomDivider} /> </View> ); }; const ShowEditPassword = () => { const password = useSelector((state: State) => state.user.password); const [hidePassword, setHidePassword] = useState(true); const navigation = useNavigation(); const { t } = useTranslation(); useFocusEffect( useCallback(() => { setHidePassword(true); }, []), ); let displayPassword = password; if (hidePassword) { displayPassword = '*'.repeat(password.length); } return ( <View style={styles.showEditPasswordContainer}> <Text style={styles.label}> {t('profile.text.backupPasswordTitle', 'Backup password')} </Text> <View style={styles.passwordInfoContainer}> <Text style={styles.passwordInfoText}> {t('signup.text.passwordInfo')} </Text> </View> {password ? ( <> <View style={styles.viewPasswordContainer}> <TouchableOpacity onPress={() => { setHidePassword(!hidePassword); }} > <Text style={styles.passwordText}> {t('profile.text.viewPassword')} </Text> </TouchableOpacity> <Text style={styles.displayPassword} selectable={true}> {displayPassword} </Text> </View> <TouchableOpacity style={styles.changePasswordButton} onPress={() => { navigation.navigate('ChangePassword'); }} > <Text style={styles.passwordText}> {t('profile.text.changePassword')} </Text> </TouchableOpacity> </> ) : ( <> <TouchableOpacity style={styles.setPasswordButton} onPress={() => { navigation.navigate('ChangePassword'); }} > <Text style={styles.setPasswordText}> {t('profile.text.setPassword')} </Text> </TouchableOpacity> </> )} </View> ); }; export const EditProfileScreen = ({ navigation }) => { const dispatch = useDispatch(); const { t } = useTranslation(); let headerHeight = useHeaderHeight(); if (DEVICE_IOS && DEVICE_LARGE) { headerHeight += 7; } const isDrawerOpen = useIsDrawerOpen(); // selectors const id = useSelector((state: State) => state.user.id); const prevPhotoFilename = useSelector( (state: State) => state.user.photo.filename, ); const prevName = useSelector((state: State) => state.user.name); const prevPhoto = useRef(null); // state passed down to children const [profilePhoto, setProfilePhoto] = useState(prevPhoto?.current); const [nextName, setNextName] = useState(prevName); // allow user to save changes if profilePhoto or name has changed const saveDisabled = (prevPhoto.current === profilePhoto && prevName === nextName) || nextName.length < 2; // profilePhoto / name is only saved to filesystem / redux if the user presses save const saveData = async () => { if (nextName.length >= 2) { dispatch(setName(nextName)); } if (prevPhoto.current !== profilePhoto) { const filename = await saveImage({ imageName: id, base64Image: profilePhoto, }); dispatch(setPhoto({ filename })); // reset state to disable save button setProfilePhoto(''); } }; const clearData = useCallback(() => { setNextName(prevName); setProfilePhoto(prevPhoto?.current); }, [prevName, setProfilePhoto, setNextName]); // clear data on focus useFocusEffect(clearData); // convert prevPhoto to base64 uri on focus useFocusEffect( useCallback(() => { if (!profilePhoto) { retrieveImage(prevPhotoFilename).then((base64Img) => { prevPhoto.current = base64Img; setProfilePhoto(base64Img); }); } }, [profilePhoto, prevPhotoFilename]), ); useEffect( () => navigation.addListener('beforeRemove', (e) => { if (saveDisabled) { // If we don't have unsaved changes, then we don't need to do anything return; } // Prevent default behavior of leaving the screen e.preventDefault(); // Prompt the user before leaving the screen Alert.alert( t('profile.alert.title.discardChanges'), t('profile.alert.text.discardChanges'), [ { text: t('profile.alert.button.dontLeave'), style: 'cancel', onPress: () => null, }, { text: t('profile.alert.button.discard'), style: 'destructive', onPress: () => navigation.dispatch(e.data.action), }, ], ); }), [navigation, saveDisabled, t], ); return ( <View style={[ styles.container, { marginTop: headerHeight }, !isDrawerOpen && styles.shadow, ]} testID="editProfileScreen" > <ScrollView contentContainerStyle={styles.contentContainer}> <EditProfilePhoto profilePhoto={profilePhoto} setProfilePhoto={setProfilePhoto} /> <EditName nextName={nextName} setNextName={setNextName} /> <SocialMediaLinks /> <ShowEditPassword /> <View style={styles.saveContainer}> <TouchableOpacity style={[ styles.saveButton, { opacity: saveDisabled ? 0.5 : 1, }, ]} disabled={saveDisabled} onPress={saveData} > <Text style={styles.saveButtonText}>{t('common.button.save')}</Text> </TouchableOpacity> <TouchableOpacity style={[ styles.cancelButton, { opacity: saveDisabled ? 0.5 : 1, }, ]} disabled={saveDisabled} onPress={clearData} > <Text style={styles.cancelButtonText}> {t('common.button.cancel')} </Text> </TouchableOpacity> </View> </ScrollView> </View> ); }; const styles = StyleSheet.create({ container: { backgroundColor: WHITE, flex: 1, width: '100%', borderTopLeftRadius: DEVICE_LARGE ? 50 : 40, paddingHorizontal: DEVICE_LARGE ? 40 : 30, }, shadow: { shadowColor: 'rgba(196, 196, 196, 0.25)', shadowOpacity: 1, shadowRadius: 15, elevation: 15, shadowOffset: { width: 0, height: 2, }, }, contentContainer: { flex: 1, width: '100%', }, profilePhotoContainer: { marginTop: DEVICE_LARGE ? 20 : 18, }, changePhotoButton: { alignItems: 'center', justifyContent: 'center', }, profilePhotoText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[16], color: BLUE, marginTop: DEVICE_LARGE ? 6 : 5, }, photo: { width: DEVICE_LARGE ? 90 : 78, height: DEVICE_LARGE ? 90 : 78, borderRadius: 71, shadowColor: 'rgba(0, 0, 0, 0.5)', shadowOffset: { width: 0, height: 2 }, shadowRadius: 4, }, editNameContainer: { width: '100%', marginTop: DEVICE_LARGE ? 36 : 30, }, label: { fontFamily: 'Poppins-Medium', fontSize: fontSize[11], color: DARK_ORANGE, }, editNameInput: { fontFamily: 'Poppins-Medium', fontSize: fontSize[16], marginTop: DEVICE_LARGE ? 4 : 2, width: '100%', color: BLACK, }, bottomDivider: { width: '100%', borderBottomColor: LIGHT_GREY, borderBottomWidth: 1, marginTop: DEVICE_LARGE ? 16 : 12, }, socialMediaContainer: { width: '100%', marginTop: DEVICE_LARGE ? 18 : 16, }, socialMediaLinkContainer: { width: WIDTH - (DEVICE_LARGE ? 80 : 60), maxWidth: WIDTH - (DEVICE_LARGE ? 80 : 60), flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: DEVICE_LARGE ? 10 : 8, }, socialMediaLinkLabel: { flexDirection: 'row', alignItems: 'center', }, socialMediaSelect: { flexDirection: 'row', alignItems: 'center', marginRight: DEVICE_LARGE ? 14 : 12, }, socialMediaType: { fontFamily: 'Poppins-Medium', fontSize: fontSize[16], color: DARK_BLUE, marginRight: DEVICE_LARGE ? 8 : 6, }, addSocialMediaBtn: { justifyContent: 'center', alignItems: 'center', marginLeft: DEVICE_LARGE ? 6 : 4, }, socialMediaInput: { fontFamily: 'Poppins-Light', fontSize: fontSize[14], color: BLACK, }, showEditPasswordContainer: { width: '100%', marginTop: DEVICE_LARGE ? 10 : 8, }, viewPasswordContainer: { width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: DEVICE_LARGE ? 26 : 18, }, changePasswordButton: { marginTop: DEVICE_LARGE ? 12 : 8, }, setPasswordButton: { marginTop: DEVICE_LARGE ? 12 : 8, alignSelf: 'center', }, passwordText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[13], color: DARK_BLUE, }, setPasswordText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[15], color: DARK_BLUE, }, displayPassword: { fontFamily: 'Poppins-Regular', fontSize: fontSize[13], color: BLACK, }, passwordInfoContainer: {}, passwordInfoText: { fontFamily: 'Poppins-Regular', fontSize: fontSize[11], color: DARKER_GREY, }, saveContainer: { width: '100%', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: DEVICE_LARGE ? 44 : 36, }, saveButton: { width: DEVICE_LARGE ? 100 : 88, paddingTop: 10, paddingBottom: 9, backgroundColor: GREEN, alignItems: 'center', justifyContent: 'center', borderRadius: 20, marginRight: DEVICE_LARGE ? 22 : 18, }, saveButtonText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[12], }, cancelButton: { width: DEVICE_LARGE ? 100 : 88, paddingTop: 10, paddingBottom: 9, backgroundColor: WHITE, alignItems: 'center', justifyContent: 'center', borderRadius: 20, borderWidth: 1, borderColor: DARKER_GREY, }, cancelButtonText: { fontFamily: 'Poppins-Medium', fontSize: fontSize[12], color: DARKER_GREY, }, closeButton: { paddingHorizontal: DEVICE_LARGE ? 10 : 8, marginRight: DEVICE_LARGE ? -10 : -8, }, }); export default EditProfileScreen;
the_stack
// tslint:disable:max-func-body-length no-non-null-assertion no-invalid-template-strings import * as assert from "assert"; import { getResourcesInfo, IGotoResourcesArgs, IJsonResourceInfo, ParentOrChildCodeLens, sortArray } from "../extension.bundle"; import { IPartialDeploymentTemplate } from "./support/diagnostics"; import { parseTemplate } from "./support/parseTemplate"; suite("ParentAndChildCodeLenses", () => { type Expected = [/*resourceName:*/ string, /*lensTitle:*/ string, /*targetStartLines:*/ number[] | undefined]; function createTest( name: string, template: IPartialDeploymentTemplate, expected: Expected[] ): void { test(name, async () => { const dt = parseTemplate(template, [], { ignoreInfos: true }); const lenses: ParentOrChildCodeLens[] = dt.getCodeLenses(undefined).filter(cl => cl instanceof ParentOrChildCodeLens) as ParentOrChildCodeLens[]; const allInfos: IJsonResourceInfo[] = []; for (const scope of dt.allScopes) { const infos = getResourcesInfo({ scope, recognizeDecoupledChildren: false }); allInfos.push(...infos); } const actual: Expected[] = []; for (const lens of lenses) { await lens.resolve(); // Find the resource the lens is inside const enclosingResources: IJsonResourceInfo[] = allInfos.filter(info => info.resourceObject.span.startIndex <= lens.span.startIndex && info.resourceObject.span.endIndex >= lens.span.endIndex); // If more than one, take the one that starts last, which will be the innermost const res = sortArray(enclosingResources, info => info.resourceObject.startIndex, { descending: true })[0]; assert(res, "Could not find a resource at the location of the code lens"); const targetStartLines = lens.command?.arguments ? (<IGotoResourcesArgs>lens.command.arguments[0]).targets.map(loc => loc.range.start.line) : undefined; actual.push( [ res.getFriendlyNameExpression({}) ?? '', lens.command?.title ?? '', targetStartLines ]); } assert.deepStrictEqual(actual, expected); }); } createTest( "single resource", { resources: [ { name: "self", type: "microsoft.abc/def" } ] }, [ // Not showing if not applicable (#1009) ["self", "No parent", undefined], // Not showing if not applicable (#1009) ["self", "No children", undefined] ]); createTest( "single resource on single line", { resources: [ { name: "self", type: "microsoft.abc/def" } ] }, [ // Not showing if not applicable (#1009) ["self", "No parent", undefined], // Not showing if not applicable (#1009) ["self", "No children", undefined] ]); suite("nested children", () => { createTest( "single nested child", { resources: [ { name: "parent", type: "microsoft.abc/def", resources: [ { name: "parent/child", type: "microsoft.abc/def/ghi" } ] } ] }, [ // Not showing if not applicable (#1009) ["parent", "No parent", undefined], ["parent", "1 child: child (ghi)", [6]], ["child", "Parent: parent (def)", [2]], // Not showing if not applicable (#1009) ["child", "No children", undefined], ]); createTest( "nested and decoupled child", { resources: [ { name: "parent/child2", type: "microsoft.abc/def/ghi" }, { name: "parent", type: "microsoft.abc/def", resources: [ { name: "parent/child1", type: "microsoft.abc/def/jkl" } ] } ] }, [ ["child2", "Parent: parent (def)", [6]], // Not showing if not applicable (#1009) ["child2", "No children", undefined], // Not showing if not applicable (#1009) ["parent", "No parent", undefined], ["parent", "2 children: child1 (jkl), child2 (ghi)", [10, 2]], // sorted by short name ["child1", "Parent: parent (def)", [6]], // Not showing if not applicable (#1009) ["child1", "No children", undefined], ]); }); createTest( "nested template", { resources: [ { type: "Microsoft.Resources/deployments", apiVersion: "2019-10-01", name: "inner1", properties: { expressionEvaluationOptions: { scope: "inner" }, mode: "Incremental", template: { resources: [ { name: "virtualNetwork1", type: "Microsoft.Network/virtualNetworks", tags: { displayName: "virtualNetwork1" }, properties: { subnets: [ { name: "Subnet-1" }, { name: "Subnet-2" } ] } } ] } } }, { type: "Microsoft.Resources/deployments", apiVersion: "2019-10-01", name: "outer1", properties: { expressionEvaluationOptions: { scope: "outer" }, mode: "Incremental", template: { resources: [ { name: "virtualNetwork1", type: "Microsoft.Network/virtualNetworks", tags: { displayName: "virtualNetwork1" }, properties: { subnets: [ { name: "Subnet-1" }, { name: "Subnet-2" } ] } } ] } } }, { condition: "[equals(parameters('vnet-new-or-existing'), 'existing')]", apiVersion: "2019-11-01", type: "Microsoft.Network/virtualNetworks/subnets", name: "[concat(parameters('vnet-name'), '/', variables('bastion-subnet-name'))]", }, { condition: "[equals(parameters('vnet-new-or-existing'), 'new')]", apiVersion: "2019-11-01", name: "[parameters('vnet-name')]", type: "Microsoft.Network/virtualNetworks", properties: { subnets: [ { name: "[variables('bastion-subnet-name')]" } ] } } ], parameters: { "vnet-new-or-existing": { }, "vnet-name": { } }, variables: { "bastion-subnet-name": "" } }, [ /* Not showing if not applicable (#1009) [ "inner1", "No parent", undefined], [ "inner1", "No children", undefined ], [ "outer1", "No parent", undefined ], [ "outer1", "No children", undefined ],*/ [ "${bastion-subnet-name}", "Parent: ${vnet-name} (virtualNetworks)", [ 72 ] ], /* Not showing if not applicable (#1009) [ "${bastion-subnet-name}", "No children", undefined ], [ "${vnet-name}", "No parent", undefined ],*/ [ "${vnet-name}", "2 children: ${bastion-subnet-name} (subnets), ${bastion-subnet-name} (subnets)", [ 79, 66 ] ], [ "${bastion-subnet-name}", "Parent: ${vnet-name} (virtualNetworks)", [ 72 ] ], /* Not showing if not applicable (#1009) [ "${bastion-subnet-name}", "No children", undefined ], [ "virtualNetwork1", "No parent", undefined ],*/ [ "virtualNetwork1", "2 children: Subnet-1 (subnets), Subnet-2 (subnets)", [ 21, 24 ] ], [ "Subnet-1", "Parent: virtualNetwork1 (virtualNetworks)", [ 13 ] ], /* Not showing if not applicable (#1009) [ "Subnet-1", "No children", undefined ],*/ [ "Subnet-2", "Parent: virtualNetwork1 (virtualNetworks)", [ 13 ] ], /* Not showing if not applicable (#1009) [ "Subnet-2", "No children", undefined ], [ "virtualNetwork1", "No parent", undefined ],*/ [ "virtualNetwork1", "2 children: Subnet-1 (subnets), Subnet-2 (subnets)", [ 53, 56 ] ], [ "Subnet-1", "Parent: virtualNetwork1 (virtualNetworks)", [ 45 ] ], /* Not showing if not applicable (#1009) [ "Subnet-1", "No children", undefined ],*/ [ "Subnet-2", "Parent: virtualNetwork1 (virtualNetworks)", [ 45 ] ] /* Not showing if not applicable (#1009) [ "Subnet-2", "No children", undefined ]*/ ]); });
the_stack
import { HttpClient } from '@angular/common/http'; import { AfterContentInit, Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { Store } from '@ngrx/store'; import { GitBranch, GitCommit, gitEntityCatalog, GitRepo, GitSCM, GitSCMService, GitSCMType } from '@stratosui/git'; import { combineLatest, combineLatest as observableCombineLatest, Observable, of as observableOf, of, Subscription, timer as observableTimer, } from 'rxjs'; import { catchError, distinctUntilChanged, filter, first, map, pairwise, publishReplay, refCount, startWith, switchMap, take, tap, withLatestFrom, } from 'rxjs/operators'; import { ProjectDoesntExist, SaveAppDetails, SetAppSourceDetails, SetBranch, SetDeployBranch, } from '../../../../../../cloud-foundry/src/actions/deploy-applications.actions'; import { CFAppState } from '../../../../../../cloud-foundry/src/cf-app-state'; import { selectDeployAppState, selectDeployBranchName, selectNewProjectCommit, selectPEProjectName, selectProjectExists, selectSourceType, } from '../../../../../../cloud-foundry/src/store/selectors/deploy-application.selector'; import { StepOnNextFunction } from '../../../../../../core/src/shared/components/stepper/step/step.component'; import { getCommitGuid } from '../../../../../../git/src/store/git-entity-factory'; import { DeployApplicationState, SourceType } from '../../../../store/types/deploy-application.types'; import { ApplicationDeploySourceTypes, DEPLOY_TYPES_IDS } from '../deploy-application-steps.types'; import { GitSuggestedRepo } from './../../../../../../git/src/store/git.public-types'; @Component({ selector: 'app-deploy-application-step2', templateUrl: './deploy-application-step2.component.html', styleUrls: ['./deploy-application-step2.component.scss'] }) export class DeployApplicationStep2Component implements OnInit, OnDestroy, AfterContentInit { @Input() isRedeploy = false; commitInfo: GitCommit; public DEPLOY_TYPES_IDS = DEPLOY_TYPES_IDS; sourceType$: Observable<SourceType>; INITIAL_SOURCE_TYPE = 0; // Fall back to GitHub, for cases where there's no type in store (refresh) or url (removed & nav) validate: Observable<boolean>; stepperText$: Observable<string>; // Observables for source types sourceTypeGithub$: Observable<boolean>; sourceTypeNeedsUpload$: Observable<boolean>; // tslint:disable-next-line:ban-types canDeployType$: Observable<Boolean>; isLoading$: Observable<boolean>; // Local FS data when file or folder upload // @Input('fsSourceData') fsSourceData; // ---- GIT ---------- repositoryBranches$: Observable<GitBranch[]>; projectInfo$: Observable<GitRepo>; commitSubscription: Subscription; sourceType: SourceType; repositoryBranch: GitBranch = null; repository: string; scm: GitSCM; cachedSuggestions = {}; // We don't have any repositories to suggest initially - need user to start typing suggestedRepos$: Observable<GitSuggestedRepo[]>; // Git URL gitUrl: string; gitUrlBranchName: string; // -------------- // ---- Docker ---------- dockerAppName: string; dockerImg: string; dockerUsername: string; // -------------- @ViewChild('sourceSelectionForm', { static: true }) sourceSelectionForm: NgForm; subscriptions: Array<Subscription> = []; @ViewChild('fsChooser') fsChooser; ngOnDestroy() { this.subscriptions.forEach(p => p.unsubscribe()); if (this.commitSubscription) { this.commitSubscription.unsubscribe(); } } constructor( private store: Store<CFAppState>, private route: ActivatedRoute, private scmService: GitSCMService, private httpClient: HttpClient, private appDeploySourceTypes: ApplicationDeploySourceTypes ) { } onNext: StepOnNextFunction = () => { // Set the details based on which source type is selected if (this.sourceType.group === 'gitscm') { gitEntityCatalog.repo.store.getRepoInfo.getEntityService({ projectName: this.repository, scm: this.scm, }).waitForEntity$.pipe(first()).subscribe(repo => { this.store.dispatch(new SaveAppDetails({ projectName: this.repository, branch: this.repositoryBranch, url: repo.entity.clone_url, commit: this.isRedeploy ? this.commitInfo.sha : undefined, endpointGuid: this.sourceType.endpointGuid, }, null)); }); } else if (this.sourceType.id === DEPLOY_TYPES_IDS.GIT_URL) { this.store.dispatch(new SaveAppDetails({ projectName: this.gitUrl, branch: { name: this.gitUrlBranchName, guid: null, projectName: null, scmType: null, endpointGuid: null, }, endpointGuid: null }, null)); } else if (this.sourceType.id === DEPLOY_TYPES_IDS.DOCKER_IMG) { this.store.dispatch(new SaveAppDetails(null, { applicationName: this.dockerAppName, dockerImage: this.dockerImg, dockerUsername: this.dockerUsername, })); } return observableOf({ success: true, data: this.sourceSelectionForm.form.value.fsLocalSource }); }; ngOnInit() { this.sourceType$ = combineLatest( this.appDeploySourceTypes.getAutoSelectedType(this.route), this.store.select(selectSourceType), this.appDeploySourceTypes.types$.pipe(first(), map(st => st[this.INITIAL_SOURCE_TYPE])) ).pipe( map(([sourceFromParam, sourceFromStore, sourceDefault]) => sourceFromParam || sourceFromStore || sourceDefault), filter(sourceType => !!sourceType), ); this.sourceTypeGithub$ = this.sourceType$.pipe( filter(type => type && !!type.id), map(type => type.group === 'gitscm') ); this.sourceTypeNeedsUpload$ = this.sourceType$.pipe( filter(type => type && !!type.id), map(type => type.id === DEPLOY_TYPES_IDS.FOLDER || type.id === DEPLOY_TYPES_IDS.FILE) ); const setInitialSourceType$ = this.sourceType$.pipe( first(), tap(sourceType => { this.setSourceType(sourceType); this.sourceType = sourceType; }) ); const cfGuid$ = this.store.select(selectDeployAppState).pipe( filter((appDetail: DeployApplicationState) => !!appDetail.cloudFoundryDetails), map((appDetail: DeployApplicationState) => appDetail.cloudFoundryDetails.cloudFoundry) ); this.canDeployType$ = combineLatest([ cfGuid$, this.sourceType$ ]).pipe( filter(([cfGuid, sourceType]) => !!cfGuid && !!sourceType), switchMap(([cfGuid, sourceType]) => this.appDeploySourceTypes.canDeployType(cfGuid, sourceType.id)), publishReplay(1), refCount() ); this.stepperText$ = this.canDeployType$.pipe( switchMap(canDeployType => canDeployType ? this.isRedeploy ? of('Review source details') : this.sourceType$.pipe(map(st => st.helpText)) : of(null) ) ); this.subscriptions.push(setInitialSourceType$.subscribe()); } setSourceType = (sourceType: SourceType) => { if (sourceType.group === 'gitscm' || sourceType.id === DEPLOY_TYPES_IDS.GIT_URL) { this.setupForGit(); } this.store.dispatch(new SetAppSourceDetails(sourceType)); }; ngAfterContentInit() { this.validate = this.sourceSelectionForm.statusChanges.pipe(map(() => { return this.sourceSelectionForm.valid || this.isRedeploy; })); } /* Git ------------------*/ private setupForGit() { this.projectInfo$ = this.store.select(selectProjectExists).pipe( filter(p => !!p), map(p => (!!p.exists && !!p.data) ? p.data : null), tap(p => { if (!!p && !this.isRedeploy) { this.store.dispatch(new SetDeployBranch(p.default_branch)); } }) ); const deployBranchName$ = this.store.select(selectDeployBranchName); const deployCommit$ = this.store.select(selectNewProjectCommit); this.repositoryBranches$ = this.store .select(selectProjectExists) .pipe( // Wait for a new project name change filter(state => state && !state.checking && !state.error && state.exists), distinctUntilChanged((x, y) => x.name.toLowerCase() === y.name.toLowerCase()), // Convert project name into branches pagination observable switchMap(state => gitEntityCatalog.branch.store.getPaginationService(null, null, { scm: this.scm, projectName: state.name }).entities$ ), // Find the specific branch we're interested in withLatestFrom(deployBranchName$), filter(([, branchName]) => !!branchName), tap(([branches, branchName]) => { this.repositoryBranch = branches.find( branch => branch.name === branchName ); }), map(([branches, branchName]) => branches), publishReplay(1), refCount() ); const updateBranchAndCommit = observableCombineLatest( this.repositoryBranches$, deployBranchName$, this.projectInfo$, deployCommit$, ).pipe( tap(([branches, name, projectInfo, commit]) => { const branch = branches.find(b => b.name === name); if (branch && !!projectInfo && branch.projectName === projectInfo.full_name) { this.store.dispatch(new SetBranch(branch)); if (this.isRedeploy) { const commitSha = commit || branch.commit.sha; const commitGuid = getCommitGuid(this.scm.getType(), projectInfo.full_name, commitSha); const commitEntityService = gitEntityCatalog.commit.store.getEntityService(commitGuid, null, { projectName: projectInfo.full_name, scm: this.scm, commitSha }); if (this.commitSubscription) { this.commitSubscription.unsubscribe(); } this.commitSubscription = commitEntityService.waitForEntity$.pipe( first(), map(p => p.entity), tap(p => this.commitInfo = p), ).subscribe(); } } }) ); this.subscriptions.push(updateBranchAndCommit.subscribe()); const setSourceTypeModel$ = this.store.select(selectSourceType).pipe( filter(p => !!p), withLatestFrom(this.appDeploySourceTypes.types$), tap(([p, sourceTypes]) => { this.sourceType = sourceTypes.find(s => s.id === p.id && (p.endpointGuid ? s.endpointGuid === p.endpointGuid : true)); const newScm = this.scmService.getSCM(this.sourceType.id as GitSCMType, this.sourceType.endpointGuid); if (!!newScm) { // User selected one of the SCM options if (this.scm && newScm.getType() !== this.scm.getType()) { // User changed the SCM type, so reset the project and branch this.repository = null; this.commitInfo = null; this.repositoryBranch = null; this.store.dispatch(new SetBranch(null)); this.store.dispatch(new ProjectDoesntExist('')); this.store.dispatch(new SaveAppDetails({ projectName: '', branch: null, endpointGuid: this.sourceType.endpointGuid }, null)); } this.scm = newScm; } }) ); const setProjectName = this.store.select(selectPEProjectName).pipe( filter(p => !!p), take(1), tap(p => { this.repository = p; }) ); this.subscriptions.push(setSourceTypeModel$.subscribe()); this.subscriptions.push(setProjectName.subscribe()); this.suggestedRepos$ = this.sourceSelectionForm.valueChanges.pipe( map(form => form.projectName), startWith(''), pairwise(), filter(([oldName, newName]) => oldName !== newName), switchMap(([, newName]) => this.updateSuggestedRepositories(newName)) ); } updateSuggestedRepositories(name: string): Observable<GitSuggestedRepo[]> { if (!name || name.length < 3) { return observableOf([] as GitSuggestedRepo[]); } const cacheName = this.scm.getType() + ':' + name; if (this.cachedSuggestions[cacheName]) { return observableOf(this.cachedSuggestions[cacheName]); } return observableTimer(500).pipe( take(1), switchMap(() => this.scm.getMatchingRepositories(this.httpClient, name)), catchError(e => observableOf(null)), tap(suggestions => this.cachedSuggestions[cacheName] = suggestions), ); } updateBranchName(branch: GitBranch) { this.store.dispatch(new SetDeployBranch(branch.name)); } }
the_stack
import { Rpc, TW_SAB_MUTEX_PTR, TW_SAB_MESSAGE_COUNT_PTR, mutexLock, mutexUnlock, assertNotNull, } from "common"; import { Worker, TaskWorkerRpc, TaskWorkerEvent } from "rpc_types"; import { ZerdeParser } from "zerde"; /// <reference lib="WebWorker" /> // This "task worker" is a special worker that helps convert asynchronous JavaScript APIs to synchronous, // blocking APIs. // // Consider the following example: (TODO(JP): this particular example is not implemented yet but it's the easiest example..) // // let handler = thread::spawn(|| { // // thread code // }); // handler.join(); // blocks until the thread is done // // In a naive implementation, `thread::spawn` would simply call `new Worker` in JavaScript. However, // the `handler.join()` call makes the thread block. This prevents JavaScript from actually creating // the worker, because `new Worker` is an asynchronous API which only actually spawns a new worker when // control is given back to the JavaScript event loop. So this would block forever! // // We solve this by having this task worker wait for messages on a `SharedArrayBuffer`, using // `Atomics.wait`. This way instead of calling `new Worker` in the other thread, we can append a // message, and call `Atomics.notify`. This wakes up the task worker and calls `new Worker`. // // Now, consider a more complicated example: // // let reader = request("url").unwrap(); // blocks until we have a valid HTTP connection // // This would map to a `fetch` call in JavaScript. However, that returns a Promise, and there is no way // to directly block on that Promise! Again, we can use the task worker to help, although the full flow // is quite a bit more complicated: // // * Task worker is waiting for a message on its `SharedArrayBuffer`, using `Atomics.wait`. // * User thread appends a message (containing e.g. the URL, and a pointer on the main `memory` to get // a notification when the task worker is done) and notifies the task worker using `Atomics.notify`. // * User thread uses `Atomics.wait` to wait for information back from the task worker. // * Task worker gets woken up, parses the messages, calls `fetch`, and increments `async_tasks`. // * Task worker doesn't use `Atomics.wait` to block, but instead it relinquishes control to JavaScript, // so that the JavaScript event loop can run, and call the Promise callback when done. // * In order to not miss any other messages (from other threads), the task worker uses `setTimeout` // to poll for new messages. // * The JavaScript event loop calls the Promise callback, which decrements `async_tasks`, and returns // information back to the user thread using the pointer that was supplied in the original message, // and calls Atomics.notify to wake up the user thread. // * If there aren't any other in-flight tasks (`async_tasks` is 0), the task worker blocks again to // wait for the next message, using `Atomics.wait`. // // See `initTaskWorkerSab` and `sendTaskWorkerMessage` in `common.js` for how we // communicate messages to this worker. type TaskWorkerMessage = { bytesReadReturnValPtr: number; streamId: number; bufPtr: number; bufLen: number; }; const _TASK_WORKER_INITIAL_RETURN_VALUE = -1; const TASK_WORKER_ERROR_RETURN_VALUE = -2; const TASK_WORKER_MESSAGE_TYPE_HTTP_STREAM_NEW = 1; const TASK_WORKER_MESSAGE_TYPE_HTTP_STREAM_READ = 2; const rpc = new Rpc<Worker<TaskWorkerRpc>>(self); rpc.receive(TaskWorkerEvent.Init, ({ taskWorkerSab, wasmMemory }) => { const taskWorkerSabi32 = new Int32Array(taskWorkerSab); // Number of async tasks that require the JavaScript even loop to have control. If zero, we'll // use Atomics.wait to wait for the next message, otherwise we'll use setTimeout to poll for new // messages. let asyncTasks = 0; // HTTP streams. Start IDs with 1, since 0 signifies an error. let nextStreamId = 1; const streams: Record< number, { reader: ReadableStreamDefaultReader<any>; done: boolean; values: Uint8Array[]; error: boolean; currentTwMessage: TaskWorkerMessage | undefined; } > = {}; // Send back an i32 return value, and wake up the original thread. function sendi32ReturnValue(returnValPtr: number, returnValue: number) { const memoryReturni32 = new Int32Array(wasmMemory.buffer, returnValPtr, 1); if (memoryReturni32[0] === returnValue) { throw new Error( "Have to set the return value to something different than the initial value, otherwise Atomics.notify won't do anything" ); } memoryReturni32[0] = returnValue; Atomics.notify(memoryReturni32, 0); } // Make a new read request for a given stream. We do this even if the underlying application doesn't // ask for it, so that we can return bytes in the fastest manner possible. // TODO(JP): We might want to set a limit to how much we buffer ahead? Or make it configurable per stream? function readDataIntoValuesBuffer(streamId: number) { const stream = streams[streamId]; asyncTasks++; stream.reader .read() .then((readResponse) => { asyncTasks--; if (readResponse.done) { stream.done = true; } else { stream.values.push(readResponse.value); readDataIntoValuesBuffer(streamId); } handleHttpStreamRead(streamId); }) .catch((error) => { asyncTasks--; // TODO(JP): Actually return the error to Rust at some point. For now we just print it. console.error("fetch read error", error); stream.error = true; handleHttpStreamRead(streamId); }); } // Check if we can supply a "read" call with data. There are two cases in which this can happen: // * There is a new read call, and there is a sufficient amount of data to give it. // * There is new data, and there is an existing read call to hand it to. // In other cases we buffer the data or block the read call, and wait until we have enough of both. function handleHttpStreamRead(streamId: number) { const stream = streams[streamId]; if (!stream.currentTwMessage) { // If there isn't a read call we can satisfy, bail. return; } if (stream.error) { sendi32ReturnValue( stream.currentTwMessage.bytesReadReturnValPtr, TASK_WORKER_ERROR_RETURN_VALUE ); stream.currentTwMessage = undefined; return; } if (stream.values.length === 0) { if (stream.done) { // If there isn't more data, and we've reached the end of the stream, just return that we read 0 bytes. sendi32ReturnValue(stream.currentTwMessage.bytesReadReturnValPtr, 0); stream.currentTwMessage = undefined; } // If there is no more data but we're not done yet, just bail. return; } // Read as many bytes as we can stuff in the buffer that was supplied to us from the read call. let bytesRead = 0; while ( stream.values.length > 0 && bytesRead < stream.currentTwMessage.bufLen ) { const value = stream.values[0]; const remainingBytesToRead = stream.currentTwMessage.bufLen - bytesRead; const bytesToReadFromValue = Math.min( value.byteLength, remainingBytesToRead ); const sourceBuffer = new Uint8Array( value.buffer, value.byteOffset, bytesToReadFromValue ); new Uint8Array( wasmMemory.buffer, stream.currentTwMessage.bufPtr + bytesRead, bytesToReadFromValue ).set(sourceBuffer); if (bytesToReadFromValue < value.byteLength) { // If we weren't able to read the entire buffer, replace it with a buffer containing the rest. stream.values[0] = new Uint8Array( value.buffer, value.byteOffset + bytesToReadFromValue, value.byteLength - bytesToReadFromValue ); } else { // If we read the whole buffer, remove it. stream.values.shift(); } bytesRead += bytesToReadFromValue; } // Return the number of bytes that we read. sendi32ReturnValue( stream.currentTwMessage.bytesReadReturnValPtr, bytesRead ); stream.currentTwMessage = undefined; } // Parse a message, which is formatted using `ZerdeBuilder` in Rust, so we use `ZerdeParser` in JavaScript // to decode it. function handleTwMessage(zerdeParser: ZerdeParser) { const messageType = zerdeParser.parseU32(); if (messageType == TASK_WORKER_MESSAGE_TYPE_HTTP_STREAM_NEW) { const streamIdReturnValPtr = zerdeParser.parseU32(); const url = zerdeParser.parseString(); const method = zerdeParser.parseString(); const body = zerdeParser.parseU8Slice(); const numberOfHeaders = zerdeParser.parseU32(); const headers: Record<string, string> = {}; for (let headerIndex = 0; headerIndex < numberOfHeaders; headerIndex++) { headers[zerdeParser.parseString()] = zerdeParser.parseString(); } asyncTasks++; fetch(url, { method, body, headers }) .then((response) => { asyncTasks--; if (response.ok) { const streamId = nextStreamId++; streams[streamId] = { // An asynchronous reader, which returns "chunks"/"values" of data. // TODO(JP): Switch to "byob" when that's supported here; see // https://bugs.chromium.org/p/chromium/issues/detail?id=614302#c23 reader: assertNotNull(response.body).getReader(), // The buffered "chunks"/"values". values: [], // Whether we've read the whole stream into `values`. done: false, // Whether we encountered an error during reading. error: false, // The current read message to return data for, if any. currentTwMessage: undefined, }; readDataIntoValuesBuffer(streamId); sendi32ReturnValue(streamIdReturnValPtr, streamId); } else { // TODO(JP): Actually return the status code to Rust at some point. For now you'll just // have to look at the Network tab of the browser's developer tools. sendi32ReturnValue( streamIdReturnValPtr, TASK_WORKER_ERROR_RETURN_VALUE ); } }) .catch((error) => { asyncTasks--; // TODO(JP): Actually return the error to Rust at some point. For now we just print it. console.error("fetch create error", error); sendi32ReturnValue( streamIdReturnValPtr, TASK_WORKER_ERROR_RETURN_VALUE ); }); } else if (messageType == TASK_WORKER_MESSAGE_TYPE_HTTP_STREAM_READ) { // http_stream_read const twMessage: TaskWorkerMessage = { bytesReadReturnValPtr: zerdeParser.parseU32(), streamId: zerdeParser.parseU32(), bufPtr: zerdeParser.parseU32(), bufLen: zerdeParser.parseU32(), }; if (streams[twMessage.streamId].currentTwMessage) { // TODO(JP): Actually return the error to Rust at some point. For now we just print it. console.error("Got multiple http_stream_read messages in a row"); sendi32ReturnValue( twMessage.bytesReadReturnValPtr, TASK_WORKER_ERROR_RETURN_VALUE ); return; } streams[twMessage.streamId].currentTwMessage = twMessage; handleHttpStreamRead(twMessage.streamId); } } function process() { // eslint-disable-next-line no-constant-condition while (true) { // Check if there are any messages. We do this without setting the Mutex, since // assume that reads are always safe. Worse case we read an incorrect value, but // a few lines down we read it again after having the Mutex. if (Atomics.load(taskWorkerSabi32, TW_SAB_MESSAGE_COUNT_PTR) > 0) { mutexLock(taskWorkerSabi32, TW_SAB_MUTEX_PTR); // Read the number of messages again now that we have the Mutex. const numberOfMessages = taskWorkerSabi32[1]; // Handle all messages. for ( let messageIndex = 0; messageIndex < numberOfMessages; messageIndex++ ) { // Use unsigned numbers for the actual pointer, since they can be >2GB. const messagePtr = new Uint32Array(taskWorkerSab)[messageIndex + 2]; handleTwMessage(new ZerdeParser(wasmMemory, messagePtr)); } // Reset the number of messages to 0. taskWorkerSabi32[TW_SAB_MESSAGE_COUNT_PTR] = 0; mutexUnlock(taskWorkerSabi32, TW_SAB_MUTEX_PTR); } if (asyncTasks > 0) { // We can't block if we have any async tasks currently running, since we need // the JavaScript event loop to be in control. So we queue up a new call to // this function (which will be handled by the event loop!) and bail. setTimeout(process, 1); break; } else { // Otherwise, we can safely block to wait for the next message. Atomics.wait(taskWorkerSabi32, 1, 0); } } } // Queue up the first call to `process`. Don't call it directly, because it will likely immediately block, // and it's nice to resolve the Promise associated with this "init" call (even though currently we don't // actually use it). setTimeout(process, 0); });
the_stack
import {expect} from 'chai'; import * as Rx from '../../dist/cjs/Rx'; import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports declare const { asDiagram, type }; declare const hot: typeof marbleTestingSignature.hot; declare const cold: typeof marbleTestingSignature.cold; declare const expectObservable: typeof marbleTestingSignature.expectObservable; declare const expectSubscriptions: typeof marbleTestingSignature.expectSubscriptions; const Observable = Rx.Observable; /** @test {mergeMapTo} */ describe('Observable.prototype.mergeMapTo', () => { asDiagram('mergeMapTo( 10\u2014\u201410\u2014\u201410\u2014| )') ('should map-and-flatten each item to an Observable', () => { const e1 = hot('--1-----3--5-------|'); const e1subs = '^ !'; const e2 = cold('x-x-x| ', {x: 10}); const expected = '--x-x-x-x-xxxx-x---|'; const values = {x: 10}; const result = e1.mergeMapTo(e2); expectObservable(result).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many regular interval inners', () => { const x = cold('----1---2---3---(4|) '); const xsubs = ['^ ! ', // ----1---2---3---(4|) ' ^ ! ', // ----1---2---3---(4|) ' ^ ! ', // ----1---2---3---(4|) ' ^ ! ']; const e1 = hot('a---b-----------c-------d-------| '); const e1subs = '^ !'; const expected = '----1---(21)(32)(43)(41)2---(31)(42)3---(4|)'; const source = e1.mergeMapTo(x); expectObservable(source).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should map values to constant resolved promises and merge', (done: MochaDone) => { const source = Rx.Observable.from([4, 3, 2, 1]); const results = []; source.mergeMapTo(Observable.from(Promise.resolve(42))).subscribe( (x: any) => { results.push(x); }, (err: any) => { done(new Error('Subscriber error handler not supposed to be called.')); }, () => { expect(results).to.deep.equal([42, 42, 42, 42]); done(); }); }); it('should map values to constant rejected promises and merge', (done: MochaDone) => { const source = Rx.Observable.from([4, 3, 2, 1]); source.mergeMapTo(Observable.from(Promise.reject(42))).subscribe( (x: any) => { done(new Error('Subscriber next handler not supposed to be called.')); }, (err: any) => { expect(err).to.equal(42); done(); }, () => { done(new Error('Subscriber complete handler not supposed to be called.')); }); }); it('should mergeMapTo values to resolved promises with resultSelector', (done: MochaDone) => { const source = Rx.Observable.from([4, 3, 2, 1]); const resultSelectorCalledWith = []; const inner = Observable.from(Promise.resolve(42)); const resultSelector = function (outerVal, innerVal, outerIndex, innerIndex) { resultSelectorCalledWith.push([].slice.call(arguments)); return 8; }; const results = []; const expectedCalls = [ [4, 42, 0, 0], [3, 42, 1, 0], [2, 42, 2, 0], [1, 42, 3, 0], ]; source.mergeMapTo(inner, resultSelector).subscribe( (x: any) => { results.push(x); }, (err: any) => { done(new Error('Subscriber error handler not supposed to be called.')); }, () => { expect(results).to.deep.equal([8, 8, 8, 8]); expect(resultSelectorCalledWith).to.deep.equal(expectedCalls); done(); }); }); it('should mergeMapTo values to rejected promises with resultSelector', (done: MochaDone) => { const source = Rx.Observable.from([4, 3, 2, 1]); const inner = Observable.from(Promise.reject(42)); const resultSelector = () => { throw 'this should not be called'; }; source.mergeMapTo(inner, resultSelector).subscribe( (x: any) => { done(new Error('Subscriber next handler not supposed to be called.')); }, (err: any) => { expect(err).to.equal(42); done(); }, () => { done(new Error('Subscriber complete handler not supposed to be called.')); }); }); it('should mergeMapTo many outer values to many inner values', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------| '); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ !']; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)(lj)k---l---|'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, complete late', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-----------------------|'); const e1subs = '^ !'; const inner = cold('----i---j---k---l---|', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ ! ']; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)(lj)k---l-------|'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, outer never completes', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------e---------------f------'); const e1subs = '^ !'; const inner = cold( '----i---j---k---l---|', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ !']; const unsub = ' !'; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)(lj)(ki)(lj)k---l---i-'; const source = e1.mergeMapTo(inner); expectObservable(source, unsub).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should not break unsubscription chains when result is unsubscribed explicitly', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------e---------------f------'); const e1subs = '^ !'; const inner = cold( '----i---j---k---l---|', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ ! ', ' ^ !']; const unsub = ' !'; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)(lj)(ki)(lj)k---l---i-'; const source = e1 .map(function (x) { return x; }) .mergeMapTo(inner) .map(function (x) { return x; }); expectObservable(source, unsub).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, inner never completes', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------| '); const e1subs = '^ '; const inner = cold('----i---j---k---l-', values); const innersubs = [' ^ ', ' ^ ', ' ^ ', ' ^ ']; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)(lj)k---l-'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, and inner throws', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------|'); const e1subs = '^ ! '; const inner = cold('----i---j---k---l-------# ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ ! ', ' (^!) ']; const expected = '-----i---j---(ki)(lj)(ki)#'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, and outer throws', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------#'); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ !', ' ^ !']; const expected = '-----i---j---(ki)(lj)(ki)(lj)(ki)#'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to many inner, both inner and outer throw', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c-------d-------#'); const e1subs = '^ !'; const inner = cold('----i---j---k---l---#', values); const innersubs = [' ^ !', ' ^ !', ' ^ !']; const expected = '-----i---j---(ki)(lj)#'; expectObservable(e1.mergeMapTo(inner)).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many cold Observable, with parameter concurrency=1', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c---| '); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ !']; const expected = '-----i---j---k---l-------i---j---k---l-------i---j---k---l---|'; function resultSelector(oV, iV, oI, iI) { return iV; } const result = e1.mergeMapTo(inner, resultSelector, 1); expectObservable(result).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMap to many cold Observable, with parameter concurrency=2', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c---| '); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ !']; const expected = '-----i---j---(ki)(lj)k---(li)j---k---l---|'; function resultSelector(oV, iV, oI, iI) { return iV; } const result = e1.mergeMapTo(inner, resultSelector, 2); expectObservable(result).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many cold Observable, with parameter concurrency=1, without resultSelector', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c---| '); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ !']; const expected = '-----i---j---k---l-------i---j---k---l-------i---j---k---l---|'; const result = e1.mergeMapTo(inner, 1); expectObservable(result).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMap to many cold Observable, with parameter concurrency=2, without resultSelector', () => { const values = {i: 'foo', j: 'bar', k: 'baz', l: 'qux'}; const e1 = hot('-a-------b-------c---| '); const e1subs = '^ !'; const inner = cold('----i---j---k---l---| ', values); const innersubs = [' ^ ! ', ' ^ ! ', ' ^ !']; const expected = '-----i---j---(ki)(lj)k---(li)j---k---l---|'; const result = e1.mergeMapTo(inner, 2); expectObservable(result).toBe(expected, values); expectSubscriptions(inner.subscriptions).toBe(innersubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to arrays', () => { const e1 = hot('2-----4--------3--------2-------|'); const e1subs = '^ !'; const expected = '(0123)(0123)---(0123)---(0123)--|'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3']); expectObservable(source).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, using resultSelector', () => { const e1 = hot('2-----4--------3--------2-------|'); const e1subs = '^ !'; const expected = '(2345)(4567)---(3456)---(2345)--|'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3'], (x: string, y: string) => String(parseInt(x) + parseInt(y))); expectObservable(source).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, and outer throws', () => { const e1 = hot('2-----4--------3--------2-------#'); const e1subs = '^ !'; const expected = '(0123)(0123)---(0123)---(0123)--#'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3']); expectObservable(source).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, resultSelector, outer throws', () => { const e1 = hot('2-----4--------3--------2-------#'); const e1subs = '^ !'; const expected = '(2345)(4567)---(3456)---(2345)--#'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3'], (x: string, y: string) => String(parseInt(x) + parseInt(y))); expectObservable(source).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, outer gets unsubscribed', () => { const e1 = hot('2-----4--------3--------2-------|'); const e1subs = '^ !'; const unsub = ' !'; const expected = '(0123)(0123)--'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3']); expectObservable(source, unsub).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, resultSelector, outer unsubscribed', () => { const e1 = hot('2-----4--------3--------2-------|'); const e1subs = '^ !'; const unsub = ' !'; const expected = '(2345)(4567)--'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3'], (x: string, y: string) => String(parseInt(x) + parseInt(y))); expectObservable(source, unsub).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should mergeMapTo many outer to inner arrays, resultSelector throws', () => { const e1 = hot('2-----4--------3--------2-------|'); const e1subs = '^ !'; const expected = '(2345)(4567)---#'; const source = e1.mergeMapTo(<any>['0', '1', '2', '3'], (outer: string, inner: string) => { if (outer === '3') { throw 'error'; } return String(parseInt(outer) + parseInt(inner)); }); expectObservable(source).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should map and flatten', () => { const source = Observable.of(1, 2, 3, 4).mergeMapTo(Observable.of('!')); const expected = ['!', '!', '!', '!']; let completed = false; source.subscribe((x: string) => { expect(x).to.equal(expected.shift()); }, null, () => { expect(expected.length).to.equal(0); completed = true; }); expect(completed).to.be.true; }); it('should map and flatten an Array', () => { const source = Observable.of(1, 2, 3, 4).mergeMapTo(<any>['!']); const expected = ['!', '!', '!', '!']; let completed = false; source.subscribe((x: string) => { expect(x).to.equal(expected.shift()); }, null, () => { expect(expected.length).to.equal(0); completed = true; }); expect(completed).to.be.true; }); it('should support type signatures', () => { type(() => { let o: Rx.Observable<number>; let m: Rx.Observable<string>; /* tslint:disable:no-unused-variable */ let a1: Rx.Observable<string> = o.mergeMapTo(m); let a2: Rx.Observable<string> = o.mergeMapTo(m, 3); let a3: Rx.Observable<{ o: number; i: string; }> = o.mergeMapTo(m, (o, i) => ({ o, i })); let a4: Rx.Observable<{ o: number; i: string; }> = o.mergeMapTo(m, (o, i) => ({ o, i }), 3); /* tslint:enable:no-unused-variable */ }); }); });
the_stack
import Duration, { friendlyDuration } from "./duration.js"; import Interval from "./interval.js"; import Settings from "./settings.js"; import Info from "./info.js"; import Formatter from "./impl/formatter.js"; import FixedOffsetZone from "./zones/fixedOffsetZone.js"; import Locale from "./impl/locale.js"; import { isUndefined, maybeArray, isDate, isNumber, bestBy, daysInMonth, daysInYear, isLeapYear, weeksInWeekYear, normalizeObject, roundTo, objToLocalTS } from "./impl/util.js"; import { normalizeZone } from "./impl/zoneUtil.js"; import diff from "./impl/diff.js"; import { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from "./impl/regexParser.js"; import { parseFromTokens, explainFromTokens } from "./impl/tokenParser.js"; import { gregorianToWeek, weekToGregorian, gregorianToOrdinal, ordinalToGregorian, hasInvalidGregorianData, hasInvalidWeekData, hasInvalidOrdinalData, hasInvalidTimeData } from "./impl/conversions.js"; import * as Formats from "./impl/formats.js"; import { InvalidArgumentError, ConflictingSpecificationError, InvalidUnitError, InvalidDateTimeError } from "./errors.js"; import Invalid from "./impl/invalid.js"; const INVALID = "Invalid DateTime"; const MAX_DATE = 8.64e15; function unsupportedZone(zone) { return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); } // we cache week data on the DT object and this intermediates the cache function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } // clone really means, "make a new object with these modifications". all "setters" really use this // to create a new object while only changing some of the properties function clone(inst, alts) { const current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, invalid: inst.invalid }; return new DateTime(Object.assign({}, current, alts, { old: current })); } // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) function fixOffset(localTS, o, tz) { // Our UTC time is just a guess because our offset is just a guess let utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts const o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done if (o === o2) { return [utcGuess, o]; } // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done const o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; } // convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; const d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; } // convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); } // create a new DT instance by adding a duration, adjusting for DSTs function adjustTime(inst, dur) { const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = Object.assign({}, inst.c, { year, month, day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 }), millisToAdd = Duration.fromObject({ years: dur.years - Math.trunc(dur.years), quarters: dur.quarters - Math.trunc(dur.quarters), months: dur.months - Math.trunc(dur.months), weeks: dur.weeks - Math.trunc(dur.weeks), days: dur.days - Math.trunc(dur.days), hours: dur.hours, minutes: dur.minutes, seconds: dur.seconds, milliseconds: dur.milliseconds }).as("milliseconds"), localTS = objToLocalTS(c); let [ts, o] = fixOffset(localTS, oPre, inst.zone); if (millisToAdd !== 0) { ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same o = inst.zone.offset(ts); } return { ts, o }; } // helper useful in turning the results of parsing into real dates // by handling the zone options function parseDataToDateTime(parsed, parsedZone, opts, format, text) { const { setZone, zone } = opts; if (parsed && Object.keys(parsed).length !== 0) { const interpretationZone = parsedZone || zone, inst = DateTime.fromObject( Object.assign(parsed, opts, { zone: interpretationZone, // setZone is a valid option in the calling methods, but not in fromObject setZone: undefined }) ); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid( new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`) ); } } // if you want to output a technical format (e.g. RFC 2822), this helper // helps handle the details function toTechFormat(dt, format, allowZ = true) { return dt.isValid ? Formatter.create(Locale.create("en-US"), { allowZ, forceSimple: true }).formatDateTimeFromString(dt, format) : null; } // technical time formats (e.g. the time part of ISO 8601), take some options // and this commonizes their handling function toTechTimeFormat( dt, { suppressSeconds = false, suppressMilliseconds = false, includeOffset, includeZone = false, spaceZone = false, format = "extended" } ) { let fmt = format === "basic" ? "HHmm" : "HH:mm"; if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) { fmt += format === "basic" ? "ss" : ":ss"; if (!suppressMilliseconds || dt.millisecond !== 0) { fmt += ".SSS"; } } if ((includeZone || includeOffset) && spaceZone) { fmt += " "; } if (includeZone) { fmt += "z"; } else if (includeOffset) { fmt += format === "basic" ? "ZZZ" : "ZZ"; } return toTechFormat(dt, fmt); } // defaults for unspecified units in the supported calendars const defaultUnitValues = { month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultWeekUnitValues = { weekNumber: 1, weekday: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }, defaultOrdinalUnitValues = { ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; // Units in the supported calendars, sorted by bigness const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], orderedWeekUnits = [ "weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond" ], orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units function normalizeUnit(unit) { const normalized = { year: "year", years: "year", month: "month", months: "month", day: "day", days: "day", hour: "hour", hours: "hour", minute: "minute", minutes: "minute", quarter: "quarter", quarters: "quarter", second: "second", seconds: "second", millisecond: "millisecond", milliseconds: "millisecond", weekday: "weekday", weekdays: "weekday", weeknumber: "weekNumber", weeksnumber: "weekNumber", weeknumbers: "weekNumber", weekyear: "weekYear", weekyears: "weekYear", ordinal: "ordinal" }[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. function quickDT(obj, zone) { // assume we have the higher-order units for (const u of orderedUnits) { if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } const tsNow = Settings.now(), offsetProvis = zone.offset(tsNow), [ts, o] = objToTS(obj, offsetProvis, zone); return new DateTime({ ts, zone, o }); } function diffRelative(start, end, opts) { const round = isUndefined(opts.round) ? true : opts.round, format = (c, unit) => { c = roundTo(c, round || opts.calendary ? 0 : 2, true); const formatter = end.loc.clone(opts).relFormatter(opts); return formatter.format(c, unit); }, differ = unit => { if (opts.calendary) { if (!end.hasSame(start, unit)) { return end .startOf(unit) .diff(start.startOf(unit), unit) .get(unit); } else return 0; } else { return end.diff(start, unit).get(unit); } }; if (opts.unit) { return format(differ(opts.unit), opts.unit); } for (const unit of opts.units) { const count = differ(unit); if (Math.abs(count) >= 1) { return format(count, unit); } } return format(0, opts.units[opts.units.length - 1]); } /** * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. * * A DateTime comprises of: * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. * * Here is a brief overview of the most commonly used functionality it provides: * * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month}, * {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors. * * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors. * * **Configuration** See the {@link locale} and {@link numberingSystem} accessors. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}. * * **Output**: To convert the DateTime to other representations, use the {@link toRelative}, {@link toRelativeCalendar}, {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link toMillis} and {@link toJSDate}. * * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. */ export default class DateTime { /** * @access private */ constructor(config) { const zone = config.zone || Settings.defaultZone; let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); /** * @access private */ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; let c = null, o = null; if (!invalid) { const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { [c, o] = [config.old.c, config.old.o]; } else { const ot = zone.offset(this.ts); c = tsToObj(this.ts, ot); invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; c = invalid ? null : c; o = invalid ? null : ot; } } /** * @access private */ this._zone = zone; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.invalid = invalid; /** * @access private */ this.weekData = null; /** * @access private */ this.c = c; /** * @access private */ this.o = o; /** * @access private */ this.isLuxonDateTime = true; } // CONSTRUCT /** * Create a local DateTime * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @example DateTime.local() //~> now * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 * @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00 * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 * @return {DateTime} */ static local(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({ ts: Settings.now() }); } else { return quickDT( { year, month, day, hour, minute, second, millisecond }, Settings.defaultZone ); } } /** * Create a DateTime in UTC * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 * @example DateTime.utc() //~> now * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z * @return {DateTime} */ static utc(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({ ts: Settings.now(), zone: FixedOffsetZone.utcInstance }); } else { return quickDT( { year, month, day, hour, minute, second, millisecond }, FixedOffsetZone.utcInstance ); } } /** * Create a DateTime from a Javascript Date object. Uses the default zone. * @param {Date} date - a Javascript Date object * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @return {DateTime} */ static fromJSDate(date, options = {}) { const ts = isDate(date) ? date.valueOf() : NaN; if (Number.isNaN(ts)) { return DateTime.invalid("invalid input"); } const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } return new DateTime({ ts: ts, zone: zoneToUse, loc: Locale.fromObject(options) }); } /** * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} milliseconds - a number of milliseconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ static fromMillis(milliseconds, options = {}) { if (!isNumber(milliseconds)) { throw new InvalidArgumentError( `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` ); } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start return DateTime.invalid("Timestamp out of range"); } else { return new DateTime({ ts: milliseconds, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} seconds - a number of seconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ static fromSeconds(seconds, options = {}) { if (!isNumber(seconds)) { throw new InvalidArgumentError("fromSeconds requires a numerical input"); } else { return new DateTime({ ts: seconds * 1000, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } } /** * Create a DateTime from a Javascript object with keys like 'year' and 'hour' with reasonable defaults. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.year - a year, such as 1987 * @param {number} obj.month - a month, 1-12 * @param {number} obj.day - a day of the month, 1-31, depending on the month * @param {number} obj.ordinal - day of the year, 1-365 or 366 * @param {number} obj.weekYear - an ISO week year * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday * @param {number} obj.hour - hour of the day, 0-23 * @param {number} obj.minute - minute of the hour, 0-59 * @param {number} obj.second - second of the minute, 0-59 * @param {number} obj.millisecond - millisecond of the second, 0-999 * @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() * @param {string} [obj.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }), * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' }) * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' }) * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' * @return {DateTime} */ static fromObject(obj) { const zoneToUse = normalizeZone(obj.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(unsupportedZone(zoneToUse)); } const tsNow = Settings.now(), offsetProvis = zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit, [ "zone", "locale", "outputCalendar", "numberingSystem" ]), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(obj); // cases: // just a weekday -> this week's instance of that weekday, no worries // (gregorian data or ordinal) + (weekYear or weekNumber) -> error // (gregorian month or day) + ordinal -> error // otherwise just use weeks or ordinals or gregorian, depending on what's specified if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError( "Can't mix weekYear/weekNumber units with year/month/day or ordinals" ); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor); // configure ourselves to deal with gregorian dates or week stuff let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; objNow = gregorianToWeek(objNow); } else if (containsOrdinal) { units = orderedOrdinalUnits; defaultValues = defaultOrdinalUnitValues; objNow = gregorianToOrdinal(objNow); } else { units = orderedUnits; defaultValues = defaultUnitValues; } // set default values for missing stuff let foundFirst = false; for (const u of units) { const v = normalized[u]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { normalized[u] = defaultValues[u]; } else { normalized[u] = objNow[u]; } } // make sure the values we have are in range const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalid) { return DateTime.invalid(invalid); } // compute the actual time const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({ ts: tsFinal, zone: zoneToUse, o: offsetFinal, loc }); // gregorian data + weekday serves only to validate if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { return DateTime.invalid( "mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` ); } return inst; } /** * Create a DateTime from an ISO 8601 string * @param {string} text - the ISO string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromISO('2016-05-25T09:08:34.123') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ static fromISO(text, opts = {}) { const [vals, parsedZone] = parseISODate(text); return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); } /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ static fromRFC2822(text, opts = {}) { const [vals, parsedZone] = parseRFC2822Date(text); return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); } /** * Create a DateTime from an HTTP header date * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @param {string} text - the HTTP header date * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ static fromHTTP(text, opts = {}) { const [vals, parsedZone] = parseHTTPDate(text); return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); } /** * Create a DateTime from an input string and format string. * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @see https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ static fromFormat(text, fmt, opts = {}) { if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }), [vals, parsedZone, invalid] = parseFromTokens(localeToUse, text, fmt); if (invalid) { return DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text); } } /** * @deprecated use fromFormat instead */ static fromString(text, fmt, opts = {}) { return DateTime.fromFormat(text, fmt, opts); } /** * Create a DateTime from a SQL date, time, or datetime * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @example DateTime.fromSQL('2017-05-15') * @example DateTime.fromSQL('2017-05-15 09:12:34') * @example DateTime.fromSQL('2017-05-15 09:12:34.342') * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ static fromSQL(text, opts = {}) { const [vals, parsedZone] = parseSQL(text); return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); } /** * Create an invalid DateTime. * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {DateTime} */ static invalid(reason, explanation = null) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); } const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(invalid); } else { return new DateTime({ invalid }); } } /** * Check if an object is a DateTime. Works across context boundaries * @param {object} o * @return {boolean} */ static isDateTime(o) { return (o && o.isLuxonDateTime) || false; } // INFO /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 * @return {number} */ get(unit) { return this[unit]; } /** * Returns whether the DateTime is valid. Invalid DateTimes occur when: * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 * * The DateTime was created by an operation on another invalid date * @type {boolean} */ get isValid() { return this.invalid === null; } /** * Returns an error code if this DateTime is invalid, or null if the DateTime is valid * @type {string} */ get invalidReason() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid * @type {string} */ get invalidExplanation() { return this.invalid ? this.invalid.explanation : null; } /** * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime * * @type {string} */ get locale() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime * * @type {string} */ get numberingSystem() { return this.isValid ? this.loc.numberingSystem : null; } /** * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime * * @type {string} */ get outputCalendar() { return this.isValid ? this.loc.outputCalendar : null; } /** * Get the time zone associated with this DateTime. * @type {Zone} */ get zone() { return this._zone; } /** * Get the name of the time zone. * @type {string} */ get zoneName() { return this.isValid ? this.zone.name : null; } /** * Get the year * @example DateTime.local(2017, 5, 25).year //=> 2017 * @type {number} */ get year() { return this.isValid ? this.c.year : NaN; } /** * Get the quarter * @example DateTime.local(2017, 5, 25).quarter //=> 2 * @type {number} */ get quarter() { return this.isValid ? Math.ceil(this.c.month / 3) : NaN; } /** * Get the month (1-12). * @example DateTime.local(2017, 5, 25).month //=> 5 * @type {number} */ get month() { return this.isValid ? this.c.month : NaN; } /** * Get the day of the month (1-30ish). * @example DateTime.local(2017, 5, 25).day //=> 25 * @type {number} */ get day() { return this.isValid ? this.c.day : NaN; } /** * Get the hour of the day (0-23). * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 * @type {number} */ get hour() { return this.isValid ? this.c.hour : NaN; } /** * Get the minute of the hour (0-59). * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 * @type {number} */ get minute() { return this.isValid ? this.c.minute : NaN; } /** * Get the second of the minute (0-59). * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 * @type {number} */ get second() { return this.isValid ? this.c.second : NaN; } /** * Get the millisecond of the second (0-999). * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 * @type {number} */ get millisecond() { return this.isValid ? this.c.millisecond : NaN; } /** * Get the week year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekYear //=> 2015 * @type {number} */ get weekYear() { return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; } /** * Get the week number of the week year (1-52ish). * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 * @type {number} */ get weekNumber() { return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; } /** * Get the day of the week. * 1 is Monday and 7 is Sunday * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekday //=> 4 * @type {number} */ get weekday() { return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; } /** * Get the ordinal (meaning the day of the year) * @example DateTime.local(2017, 5, 25).ordinal //=> 145 * @type {number|DateTime} */ get ordinal() { return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; } /** * Get the human readable short month name, such as 'Oct'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthShort //=> Oct * @type {string} */ get monthShort() { return this.isValid ? Info.months("short", { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable long month name, such as 'October'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthLong //=> October * @type {string} */ get monthLong() { return this.isValid ? Info.months("long", { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable short weekday, such as 'Mon'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon * @type {string} */ get weekdayShort() { return this.isValid ? Info.weekdays("short", { locale: this.locale })[this.weekday - 1] : null; } /** * Get the human readable long weekday, such as 'Monday'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday * @type {string} */ get weekdayLong() { return this.isValid ? Info.weekdays("long", { locale: this.locale })[this.weekday - 1] : null; } /** * Get the UTC offset of this DateTime in minutes * @example DateTime.local().offset //=> -240 * @example DateTime.utc().offset //=> 0 * @type {number} */ get offset() { return this.isValid ? +this.o : NaN; } /** * Get the short human name for the zone's current offset, for example "EST" or "EDT". * Defaults to the system's locale if no locale has been specified * @type {string} */ get offsetNameShort() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "short", locale: this.locale }); } else { return null; } } /** * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". * Defaults to the system's locale if no locale has been specified * @type {string} */ get offsetNameLong() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: "long", locale: this.locale }); } else { return null; } } /** * Get whether this zone's offset ever changes, as in a DST. * @type {boolean} */ get isOffsetFixed() { return this.isValid ? this.zone.universal : null; } /** * Get whether the DateTime is in a DST. * @type {boolean} */ get isInDST() { if (this.isOffsetFixed) { return false; } else { return ( this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset ); } } /** * Returns true if this DateTime is in a leap year, false otherwise * @example DateTime.local(2016).isInLeapYear //=> true * @example DateTime.local(2013).isInLeapYear //=> false * @type {boolean} */ get isInLeapYear() { return isLeapYear(this.year); } /** * Returns the number of days in this DateTime's month * @example DateTime.local(2016, 2).daysInMonth //=> 29 * @example DateTime.local(2016, 3).daysInMonth //=> 31 * @type {number} */ get daysInMonth() { return daysInMonth(this.year, this.month); } /** * Returns the number of days in this DateTime's year * @example DateTime.local(2016).daysInYear //=> 366 * @example DateTime.local(2013).daysInYear //=> 365 * @type {number} */ get daysInYear() { return this.isValid ? daysInYear(this.year) : NaN; } /** * Returns the number of weeks in this DateTime's year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2004).weeksInWeekYear //=> 53 * @example DateTime.local(2013).weeksInWeekYear //=> 52 * @type {number} */ get weeksInWeekYear() { return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; } /** * Returns the resolved Intl options for this DateTime. * This is useful in understanding the behavior of formatting methods * @param {Object} opts - the same options as toLocaleString * @return {Object} */ resolvedLocaleOpts(opts = {}) { const { locale, numberingSystem, calendar } = Formatter.create( this.loc.clone(opts), opts ).resolvedOptions(this); return { locale, numberingSystem, outputCalendar: calendar }; } // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. * * Equivalent to {@link setZone}('utc') * @param {number} [offset=0] - optionally, an offset from UTC in minutes * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ toUTC(offset = 0, opts = {}) { return this.setZone(FixedOffsetZone.instance(offset), opts); } /** * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. * * Equivalent to `setZone('local')` * @return {DateTime} */ toLocal() { return this.setZone(Settings.defaultZone); } /** * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. * * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class. * @param {Object} opts - options * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. * @return {DateTime} */ setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { zone = normalizeZone(zone, Settings.defaultZone); if (zone.equals(this.zone)) { return this; } else if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } else { let newTS = this.ts; if (keepLocalTime || keepCalendarTime) { const offsetGuess = zone.offset(this.ts); const asObj = this.toObject(); [newTS] = objToTS(asObj, offsetGuess, zone); } return clone(this, { ts: newTS, zone }); } } /** * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. * @param {Object} properties - the properties to set * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) * @return {DateTime} */ reconfigure({ locale, numberingSystem, outputCalendar } = {}) { const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); return clone(this, { loc }); } /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ setLocale(locale) { return this.reconfigure({ locale }); } /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}. * @param {Object} values - a mapping of units to numbers * @example dt.set({ year: 2017 }) * @example dt.set({ hour: 8, minute: 30 }) * @example dt.set({ weekday: 5 }) * @example dt.set({ year: 2005, ordinal: 234 }) * @return {DateTime} */ set(values) { if (!this.isValid) return this; const normalized = normalizeObject(values, normalizeUnit, []), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday); let mixed; if (settingWeekStuff) { mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized)); } else if (!isUndefined(normalized.ordinal)) { mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized)); } else { mixed = Object.assign(this.toObject(), normalized); // if we didn't set the day but we ended up on an overflow date, // use the last day of the right month if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } const [ts, o] = objToTS(mixed, this.o, this.zone); return clone(this, { ts, o }); } /** * Add a period of time to this DateTime and return the resulting DateTime * * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @example DateTime.local().plus(123) //~> in 123 milliseconds * @example DateTime.local().plus({ minutes: 15 }) //~> in 15 minutes * @example DateTime.local().plus({ days: 1 }) //~> this time tomorrow * @example DateTime.local().plus({ days: -1 }) //~> this time yesterday * @example DateTime.local().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min * @example DateTime.local().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min * @return {DateTime} */ plus(duration) { if (!this.isValid) return this; const dur = friendlyDuration(duration); return clone(this, adjustTime(this, dur)); } /** * Subtract a period of time to this DateTime and return the resulting DateTime * See {@link plus} * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() @return {DateTime} */ minus(duration) { if (!this.isValid) return this; const dur = friendlyDuration(duration).negate(); return clone(this, adjustTime(this, dur)); } /** * "Set" this DateTime to the beginning of a unit of time. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' * @return {DateTime} */ startOf(unit) { if (!this.isValid) return this; const o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o.month = 1; // falls through case "quarters": case "months": o.day = 1; // falls through case "weeks": case "days": o.hour = 0; // falls through case "hours": o.minute = 0; // falls through case "minutes": o.second = 0; // falls through case "seconds": o.millisecond = 0; break; case "milliseconds": break; // no default, invalid units throw in normalizeUnit() } if (normalizedUnit === "weeks") { o.weekday = 1; } if (normalizedUnit === "quarters") { const q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } return this.set(o); } /** * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time * @param {string} unit - The unit to go to the end of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' * @return {DateTime} */ endOf(unit) { return this.isValid ? this.plus({ [unit]: 1 }) .startOf(unit) .minus(1) : this; } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @see https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens * @param {string} fmt - the format string * @param {Object} opts - opts to override the configuration options * @example DateTime.local().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.local().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.local().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' * @example DateTime.local().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ toFormat(fmt, opts = {}) { return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; } /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param opts {Object} - Intl.DateTimeFormat constructor options and configuration options * @example DateTime.local().toLocaleString(); //=> 4/20/2017 * @example DateTime.local().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.local().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017' * @example DateTime.local().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.local().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.local().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.local().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' * @example DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' * @example DateTime.local().toLocaleString({ hour: '2-digit', minute: '2-digit', hour12: false }); //=> '11:32' * @return {string} */ toLocaleString(opts = Formats.DATE_SHORT) { return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this) : INVALID; } /** * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.local().toLocaleParts(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ toLocaleParts(opts = {}) { return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' * @example DateTime.local().toISO() //=> '2017-04-22T20:47:05.335-04:00' * @example DateTime.local().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' * @example DateTime.local().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' * @return {string} */ toISO(opts = {}) { if (!this.isValid) { return null; } return `${this.toISODate(opts)}T${this.toISOTime(opts)}`; } /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @param {Object} opts - options * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @return {string} */ toISODate({ format = "extended" } = {}) { let fmt = format === "basic" ? "yyyyMMdd" : "yyyy-MM-dd"; if (this.year > 9999) { fmt = "+" + fmt; } return toTechFormat(this, fmt); } /** * Returns an ISO 8601-compliant string representation of this DateTime's week date * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' * @return {string} */ toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); } /** * Returns an ISO 8601-compliant string representation of this DateTime's time component * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' * @return {string} */ toISOTime({ suppressMilliseconds = false, suppressSeconds = false, includeOffset = true, format = "extended" } = {}) { return toTechTimeFormat(this, { suppressSeconds, suppressMilliseconds, includeOffset, format }); } /** * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' * @return {string} */ toRFC2822() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); } /** * Returns a string representation of this DateTime appropriate for use in HTTP headers. * Specifically, the string conforms to RFC 1123. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' * @return {string} */ toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Date * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' * @return {string} */ toSQLDate() { return toTechFormat(this, "yyyy-MM-dd"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.local().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.local().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.local().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ toSQLTime({ includeOffset = true, includeZone = false } = {}) { return toTechTimeFormat(this, { includeOffset, includeZone, spaceZone: true }); } /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ toSQL(opts = {}) { if (!this.isValid) { return null; } return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; } /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ toString() { return this.isValid ? this.toISO() : INVALID; } /** * Returns the epoch milliseconds of this DateTime. Alias of {@link toMillis} * @return {number} */ valueOf() { return this.toMillis(); } /** * Returns the epoch milliseconds of this DateTime. * @return {number} */ toMillis() { return this.isValid ? this.ts : NaN; } /** * Returns the epoch seconds of this DateTime. * @return {number} */ toSeconds() { return this.isValid ? this.ts / 1000 : NaN; } /** * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. * @return {string} */ toJSON() { return this.toISO(); } /** * Returns a BSON serializable equivalent to this DateTime. * @return {Date} */ toBSON() { return this.toJSDate(); } /** * Returns a Javascript object with this DateTime's year, month, day, and so on. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example DateTime.local().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } * @return {Object} */ toObject(opts = {}) { if (!this.isValid) return {}; const base = Object.assign({}, this.c); if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; } /** * Returns a Javascript Date equivalent to this DateTime. * @return {Date} */ toJSDate() { return new Date(this.isValid ? this.ts : NaN); } // COMPARE /** * Return the difference between two DateTimes as a Duration. * @param {DateTime} otherDateTime - the DateTime to compare this one to * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example * var i1 = DateTime.fromISO('1982-05-25T09:45'), * i2 = DateTime.fromISO('1983-10-14T10:30'); * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } * @return {Duration} */ diff(otherDateTime, unit = "milliseconds", opts = {}) { if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid( this.invalid || otherDateTime.invalid, "created by diffing an invalid DateTime" ); } const durOpts = Object.assign( { locale: this.locale, numberingSystem: this.numberingSystem }, opts ); const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts); return otherIsLater ? diffed.negate() : diffed; } /** * Return the difference between this DateTime and right now. * See {@link diff} * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ diffNow(unit = "milliseconds", opts = {}) { return this.diff(DateTime.local(), unit, opts); } /** * Return an Interval spanning between this DateTime and another DateTime * @param {DateTime} otherDateTime - the other end point of the Interval * @return {Interval} */ until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; } /** * Return whether this DateTime is in the same unit of time as another DateTime * @param {DateTime} otherDateTime - the other DateTime * @param {string} unit - the unit of time to check sameness on * @example DateTime.local().hasSame(otherDT, 'day'); //~> true if both the same calendar day * @return {boolean} */ hasSame(otherDateTime, unit) { if (!this.isValid) return false; if (unit === "millisecond") { return this.valueOf() === otherDateTime.valueOf(); } else { const inputMs = otherDateTime.valueOf(); return this.startOf(unit) <= inputMs && inputMs <= this.endOf(unit); } } /** * Equality check * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid. * To compare just the millisecond values, use `+dt1 === +dt2`. * @param {DateTime} other - the other DateTime * @return {boolean} */ equals(other) { return ( this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc) ); } /** * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your * platform supports Intl.RelativeTimeFormat. Rounds down by default. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.local()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" * @param {boolean} [options.round=true] - whether to round the numbers in the output. * @param {boolean} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.local().plus({ days: 1 }).toRelative() //=> "in 1 day" * @example DateTime.local().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" * @example DateTime.local().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" * @example DateTime.local().minus({ days: 2 }).toRelative() //=> "2 days ago" * @example DateTime.local().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" * @example DateTime.local().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" */ toRelative(options = {}) { if (!this.isValid) return null; const base = options.base || DateTime.fromObject({ zone: this.zone }), padding = options.padding ? (this < base ? -options.padding : options.padding) : 0; return diffRelative( base, this.plus(padding), Object.assign(options, { numeric: "always", units: ["years", "months", "days", "hours", "minutes", "seconds"] }) ); } /** * Returns a string representation of this date relative to today, such as "yesterday" or "next month". * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.local()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.local().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" * @example DateTime.local().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" * @example DateTime.local().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" * @example DateTime.local().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" */ toRelativeCalendar(options = {}) { if (!this.isValid) return null; return diffRelative( options.base || DateTime.fromObject({ zone: this.zone }), this, Object.assign(options, { numeric: "auto", units: ["years", "months", "days"], calendary: true }) ); } /** * Return the min of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum * @return {DateTime} the min DateTime, or undefined if called with no argument */ static min(...dateTimes) { if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be DateTimes"); } return bestBy(dateTimes, i => i.valueOf(), Math.min); } /** * Return the max of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum * @return {DateTime} the max DateTime, or undefined if called with no argument */ static max(...dateTimes) { if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } return bestBy(dateTimes, i => i.valueOf(), Math.max); } // MISC /** * Explain how a string would be parsed by fromFormat() * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options taken by fromFormat() * @return {Object} */ static fromFormatExplain(text, fmt, options = {}) { const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text, fmt); } /** * @deprecated use fromFormatExplain instead */ static fromStringExplain(text, fmt, options = {}) { return DateTime.fromFormatExplain(text, fmt, options); } // FORMAT PRESETS /** * {@link toLocaleString} format like 10/14/1983 * @type {Object} */ static get DATE_SHORT() { return Formats.DATE_SHORT; } /** * {@link toLocaleString} format like 'Oct 14, 1983' * @type {Object} */ static get DATE_MED() { return Formats.DATE_MED; } /** * {@link toLocaleString} format like 'Fri, Oct 14, 1983' * @type {Object} */ static get DATE_MED_WITH_WEEKDAY() { return Formats.DATE_MED_WITH_WEEKDAY; } /** * {@link toLocaleString} format like 'October 14, 1983' * @type {Object} */ static get DATE_FULL() { return Formats.DATE_FULL; } /** * {@link toLocaleString} format like 'Tuesday, October 14, 1983' * @type {Object} */ static get DATE_HUGE() { return Formats.DATE_HUGE; } /** * {@link toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_SIMPLE() { return Formats.TIME_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_SECONDS() { return Formats.TIME_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_SHORT_OFFSET() { return Formats.TIME_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_LONG_OFFSET() { return Formats.TIME_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '09:30', always 24-hour. * @type {Object} */ static get TIME_24_SIMPLE() { return Formats.TIME_24_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23', always 24-hour. * @type {Object} */ static get TIME_24_WITH_SECONDS() { return Formats.TIME_24_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 EDT', always 24-hour. * @type {Object} */ static get TIME_24_WITH_SHORT_OFFSET() { return Formats.TIME_24_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. * @type {Object} */ static get TIME_24_WITH_LONG_OFFSET() { return Formats.TIME_24_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_SHORT() { return Formats.DATETIME_SHORT; } /** * {@link toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_SHORT_WITH_SECONDS() { return Formats.DATETIME_SHORT_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED() { return Formats.DATETIME_MED; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED_WITH_SECONDS() { return Formats.DATETIME_MED_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED_WITH_WEEKDAY() { return Formats.DATETIME_MED_WITH_WEEKDAY; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_FULL() { return Formats.DATETIME_FULL; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_FULL_WITH_SECONDS() { return Formats.DATETIME_FULL_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_HUGE() { return Formats.DATETIME_HUGE; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_HUGE_WITH_SECONDS() { return Formats.DATETIME_HUGE_WITH_SECONDS; } } /** * @private */ export function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { return DateTime.fromJSDate(dateTimeish); } else if (dateTimeish && typeof dateTimeish === "object") { return DateTime.fromObject(dateTimeish); } else { throw new InvalidArgumentError( `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` ); } }
the_stack
import { Component, OnInit, Input, Output, EventEmitter, ElementRef, AfterViewInit, OnDestroy } from '@angular/core'; import { Store } from '@ngrx/store'; import { global, authPayload } from '../../services/common'; import { roomAction } from './actions'; import { mainAction } from '../main/actions'; import { Util } from '../../services/util'; import { chatAction } from '../chat/actions'; const PageSize = 20; @Component({ selector: 'room-component', templateUrl: './room.component.html', styleUrls: ['./room.component.scss'] }) export class RoomComponent implements OnInit, AfterViewInit, OnDestroy { private roomList = []; private active: any = {}; private roomDetail = {}; private enterRoomLoading = false; private showPanel = 0; private enter: any = {}; private roomInfomation = { show: false, info: {} }; private messageList = []; private msgKey = 0; private selfInfo: any = {}; private scrollToBottom = false; private otherScrollTobottom = false; private start = 0; private loadMoreRoomsFlag = false; private rememberEnter = null; private noMoreRooms = false; private roomStream$; private voiceState = []; constructor( private store$: Store<any>, private elementRef: ElementRef ) { } public ngOnInit() { this.store$.dispatch({ type: roomAction.init, payload: null }); // 获取聊天室第一页的列表 this.store$.dispatch({ type: roomAction.getRoomList, payload: { start: this.start, appkey: authPayload.appkey } }); // 获取自己目前所在的群聊列表 this.store$.dispatch({ type: roomAction.getSelfChatrooms, payload: null }); this.roomStream$ = this.store$.select((state) => { const roomState = state['roomReducer']; const mainState = state['mainReducer']; this.stateChanged(roomState, mainState); return state; }).subscribe((state) => { // pass }); } public ngAfterViewInit() { const voiceStateKey = `voiceRoomState-${authPayload.appkey}-${global.user}`; // 获取本地存储的语音已读状态 this.store$.dispatch({ type: roomAction.getRoomVoiceState, payload: voiceStateKey }); } public ngOnDestroy() { this.roomStream$.unsubscribe(); } private stateChanged(roomState, mainState) { switch (roomState.actionType) { case roomAction.init: this.init(); break; case mainAction.showSelfInfo: if (mainState.selfInfo.info) { this.selfInfo = mainState.selfInfo.info; } break; case roomAction.exitAllChatroomsSuccess: this.watchRoomMsg(); break; case roomAction.getRoomListSuccess: this.roomList = roomState.roomList; this.loadMoreRoomsFlag = !this.loadMoreRoomsFlag; this.noMoreRooms = roomState.noMoreRooms; break; case roomAction.changeRoomSuccess: this.active = roomState.active; this.roomDetail = roomState.roomDetail; this.rememberEnter = null; this.store$.dispatch({ type: roomAction.showPanel, payload: 1 }); this.messageList = roomState.messageList; break; case mainAction.selectSearchRoomUser: this.active = roomState.active; this.roomDetail = roomState.roomDetail; this.rememberEnter = null; this.showPanel = roomState.showPanel; break; case roomAction.enterRoom: this.enterRoomLoading = roomState.enterRoomLoading; break; case roomAction.enterRoomError: this.enterRoomLoading = roomState.enterRoomLoading; break; case roomAction.enterRoomSuccess: if (this.active.id === roomState.enter.id) { this.store$.dispatch({ type: roomAction.showPanel, payload: 2 }); this.rememberEnter = this.enter = roomState.enter; this.scrollToBottom = !this.scrollToBottom; } this.messageList = roomState.messageList; this.enterRoomLoading = roomState.enterRoomLoading; break; case roomAction.showRoomInfomationSuccess: this.roomInfomation = roomState.roomInfomation; break; case roomAction.receiveMessageSuccess: this.messageList = roomState.messageList; this.otherScrollTobottom = !this.otherScrollTobottom; break; case roomAction.sendTextMsg: case roomAction.sendFileMsg: case roomAction.sendPicMsg: case roomAction.transmitPicMsg: this.otherScrollTobottom = !this.otherScrollTobottom; break; case roomAction.exitRoomSuccess: this.enter = roomState.enter; break; case mainAction.changeListTab: if (mainState.listTab === 2 && this.rememberEnter) { this.store$.dispatch({ type: roomAction.enterRoom, payload: this.rememberEnter }); } this.messageList = roomState.messageList; case mainAction.createGroup: case mainAction.selectSearchUser: case chatAction.createOtherChat: if (mainState.listTab !== 2 && this.enter.id) { this.store$.dispatch({ type: roomAction.exitRoom, payload: this.enter }); } break; case roomAction.showPanel: this.showPanel = roomState.showPanel; break; case roomAction.getRoomVoiceStateSuccess: this.voiceState = roomState.voiceRoomState; break; default: } } // 监听聊天室消息 private watchRoomMsg() { global.JIM.onRoomMsg((data) => { this.store$.dispatch({ type: roomAction.receiveMessage, payload: { data, messageList: this.messageList } }); }); } // 加载更多聊天室 private loadMoreRoomsEmit() { if (!this.noMoreRooms) { this.start += PageSize; this.store$.dispatch({ type: roomAction.getRoomList, payload: { start: this.start, appkey: authPayload.appkey } }); } } // 切换聊天室 private changeRoomEmit(room) { if (this.active.id !== room.id) { this.store$.dispatch({ type: roomAction.changeRoom, payload: room }); } } // 进入聊天室 private enterRoomEmit(room) { this.store$.dispatch({ type: roomAction.enterRoom, payload: room }); } // 显示聊天室信息 private showRoomInfomationEmit() { this.store$.dispatch({ type: roomAction.showRoomInfomation, payload: this.enter }); } // 隐藏聊天室信息 private hideRoomInfomationEmit() { this.store$.dispatch({ type: roomAction.showRoomInfomationSuccess, payload: { show: false, info: {} } }); } // 发送文本 private sendMsgEmit(data) { /** * success * 取值 状态 * 1 正在发送 * 2 发送成功 * 3 发送失败 */ if (data.repeatSend) { this.store$.dispatch({ type: roomAction.sendTextMsg, payload: { localMsg: data.repeatSend.localMsg, sendMsg: data.repeatSend.localMsg.sendMsg, repeatSend: true } }); } else { let localMsg: any = { content: { msg_type: 'text', from_id: global.user, from_name: this.selfInfo.nickname, msg_body: { text: data.content } }, ctime_ms: new Date().getTime(), success: 1, msgKey: this.msgKey++ }; let sendMsg: any = { target_rid: this.enter.id, content: data.content }; if (data.type === 'businessCard') { localMsg.content.msg_body.extras = data.localExtras; sendMsg.extras = data.extras; } this.store$.dispatch({ type: roomAction.sendTextMsg, payload: { localMsg, sendMsg, repeatSend: false } }); } } // 发送文件 private sendFileEmit(data) { if (data.repeatSend) { this.store$.dispatch({ type: roomAction.sendFileMsg, payload: { localMsg: data.repeatSend.localMsg, sendMsg: data.repeatSend.localMsg.sendMsg, repeatSend: true } }); } else { const ext = Util.getExt(data.fileData.name); const localMsg = { content: { msg_type: 'file', from_id: global.user, from_name: this.selfInfo.nickname, msg_body: { fname: data.fileData.name, fsize: data.fileData.size, extras: { fileSize: data.fileData.size, fileType: ext } } }, ctime_ms: new Date().getTime(), success: 1, msgKey: this.msgKey++ }; const sendMsg = { target_rid: this.enter.id, file: data.file, extras: { fileSize: data.fileData.size, fileType: ext } }; this.store$.dispatch({ type: roomAction.sendFileMsg, payload: { localMsg, sendMsg, repeatSend: false } }); } } // 发送图片 private sendPicEmit(data) { if (data.repeatSend) { this.store$.dispatch({ type: roomAction.sendPicMsg, payload: { localMsg: data.repeatSend.localMsg, sendMsg: data.repeatSend.localMsg.sendMsg, repeatSend: true } }); } else { if (data.type === 'paste') { this.sendPicContent(data.info, data); } else if (data.type === 'jpushEmoji') { const localMsg = { content: { from_id: global.user, from_name: this.selfInfo.nickname, msg_type: 'image', msg_body: data.jpushEmoji.body }, ctime_ms: new Date().getTime(), success: 1, msgKey: this.msgKey++ }; const sendMsg = { target_rid: this.enter.id, msg_body: { format: data.jpushEmoji.body.format, fsize: data.jpushEmoji.body.fsize, height: data.jpushEmoji.body.height, media_crc32: data.jpushEmoji.body.media_crc32, media_id: data.jpushEmoji.body.media_id, width: data.jpushEmoji.body.width, extras: { kLargeEmoticon: 'kLargeEmoticon' } } }; this.store$.dispatch({ type: roomAction.transmitPicMsg, payload: { localMsg, sendMsg, repeatSend: false } }); } else if (data.type === 'img') { const file = this.elementRef.nativeElement.querySelector('#sendPic2'); Util.imgReader(file, () => { this.store$.dispatch({ type: mainAction.showModalTip, payload: { show: true, info: { title: '提示', tip: '选择的文件必须是图片', actionType: '[chat] must be image', cancel: true } } }); }, (value) => this.sendPicContent(value, data)); } } } private sendPicContent(value, data) { const localMsg = { content: { from_id: global.user, from_name: this.selfInfo.nickname, msg_type: 'image', msg_body: { media_url: value.src, width: value.width, height: value.height } }, ctime_ms: new Date().getTime(), success: 1, msgKey: this.msgKey++ }; const sendMsg = { target_rid: this.enter.id, image: data.img, repeatSend: false }; this.store$.dispatch({ type: roomAction.sendPicMsg, payload: { localMsg, sendMsg, repeatSend: false } }); } // 消息转发 private msgTransmitEmit(item) { this.store$.dispatch({ type: roomAction.transmitAllMsg, payload: item }); } // 查看个人信息 private watchSelfInfoEmit() { this.store$.dispatch({ type: mainAction.showSelfInfo, payload: { show: true } }); } // 查看用户信息 private watchOtherInfoEmit(info) { this.store$.dispatch({ type: chatAction.watchOtherInfo, payload: info }); } // 消息面板发送名片 private businessCardSendEmit(user) { const msg = { content: '推荐了一张名片', extras: { userName: user.name, appKey: user.appkey, businessCard: 'businessCard' }, localExtras: { userName: user.name, appKey: user.appkey, businessCard: 'businessCard', media_url: user.avatarUrl, nickName: user.nickName }, type: 'businessCard' }; this.sendMsgEmit(msg); } private voiceHasPlayEmit(voice) { this.voiceState.push(voice); const voiceStateKey = `voiceRoomState-${authPayload.appkey}-${global.user}`; this.store$.dispatch({ type: roomAction.storageVoiceState, payload: { voiceState: this.voiceState, voiceStateKey } }); } // 显示视频模态框 private playVideoEmit(url) { this.store$.dispatch({ type: chatAction.playVideoShow, payload: { url, show: true } }); } private init() { this.roomList = []; this.active = {}; this.roomDetail = {}; this.enterRoomLoading = false; this.showPanel = 0; this.enter = {}; this.roomInfomation = { show: false, info: {} }; this.messageList = []; this.msgKey = 0; this.selfInfo = {}; this.scrollToBottom = false; this.otherScrollTobottom = false; this.start = 0; this.loadMoreRoomsFlag = false; this.rememberEnter = null; this.voiceState = []; } }
the_stack
* @module commonGrpc/service */ import * as path from 'path'; import { Abortable, BodyResponseCallback, DecorateRequestOptions, Service, ServiceConfig, util, } from '@google-cloud/common'; import {replaceProjectIdToken} from '@google-cloud/projectify'; import { loadSync, PackageDefinition, ServiceDefinition, } from '@grpc/proto-loader'; import * as duplexify from 'duplexify'; import {EventEmitter} from 'events'; import * as extend from 'extend'; import {grpc, GrpcClient} from 'google-gax'; import * as is from 'is'; import {Request, Response} from 'teeny-request'; import * as retryRequest from 'retry-request'; import {Duplex, PassThrough} from 'stream'; const gaxProtoPath = path.join( path.dirname(require.resolve('google-gax')), '..', 'protos' ); export interface ServiceRequestCallback { (err: Error | null, apiResponse?: Response): void; } interface RetryOptions { objectMode?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any request?: any; retries?: number; noResponseRetries?: number; currentRetryAttempt?: number; shouldRetryFn?: (response: Response) => boolean; } export interface ProtoOpts { service: string; method: string; timeout?: number; retryOpts?: RetryOptions; stream?: Duplex; } interface GrpcOptions { deadline?: Date; } /** * Configuration object for GrpcService. */ export interface GrpcServiceConfig extends ServiceConfig { /** gRPC implementation to use. By default, uses `@grpc/grpc-js`. */ grpc?: typeof grpc; /** gRPC version, to send in headers */ grpcVersion?: string; /** Metadata to send with every request. */ grpcMetadata: grpc.Metadata; /** The root directory where proto files live. */ protosDir: string; /** * Directly provide the required proto files. This is useful when a single * class requires multiple services. */ protoServices: { [serviceName: string]: {path: string; service: string; baseUrl: string}; }; customEndpoint: boolean; } // TODO: convert this object to an array /** * @const {object} - A map of protobuf codes to HTTP status codes. * @private */ const GRPC_ERROR_CODE_TO_HTTP = { 0: { code: 200, message: 'OK', }, 1: { code: 499, message: 'Client Closed Request', }, 2: { code: 500, message: 'Internal Server Error', }, 3: { code: 400, message: 'Bad Request', }, 4: { code: 504, message: 'Gateway Timeout', }, 5: { code: 404, message: 'Not Found', }, 6: { code: 409, message: 'Conflict', }, 7: { code: 403, message: 'Forbidden', }, 8: { code: 429, message: 'Too Many Requests', }, 9: { code: 412, message: 'Precondition Failed', }, 10: { code: 409, message: 'Conflict', }, 11: { code: 400, message: 'Bad Request', }, 12: { code: 501, message: 'Not Implemented', }, 13: { code: 500, message: 'Internal Server Error', }, 14: { code: 503, message: 'Service Unavailable', }, 15: { code: 500, message: 'Internal Server Error', }, 16: { code: 401, message: 'Unauthorized', }, }; /** * The default configuration for all gRPC Service instantions. * * @resource [All options]{@link * https://github.com/grpc/grpc/blob/13e185419cd177b7fb552601665e43820321a96b/include/grpc/impl/codegen/grpc_types.h#L148} * * @private * * @type {object} */ const GRPC_SERVICE_OPTIONS = { // RE: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1991 'grpc.max_send_message_length': -1, // unlimited 'grpc.max_receive_message_length': -1, // unlimited // RE: https://github.com/grpc/grpc/issues/8839 // RE: https://github.com/grpc/grpc/issues/8382 // RE: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1991 'grpc.initial_reconnect_backoff_ms': 5000, }; export interface ObjectToStructConverterConfig { removeCircular?: boolean; stringify?: boolean; } export class ObjectToStructConverter { seenObjects: Set<{}>; removeCircular: boolean; stringify?: boolean; /** * A class that can be used to convert an object to a struct. Optionally this * class can be used to erase/throw on circular references during conversion. * * @private * * @param {object=} options - Configuration object. * @param {boolean} options.removeCircular - Remove circular references in the * object with a placeholder string. (Default: `false`) * @param {boolean} options.stringify - Stringify un-recognized types. (Default: * `false`) */ constructor(options?: ObjectToStructConverterConfig) { options = options || {}; this.seenObjects = new Set(); this.removeCircular = options.removeCircular === true; this.stringify = options.stringify === true; } /** * Begin the conversion process from a JS object to an encoded gRPC Value * message. * * @param {*} value - The input value. * @return {object} - The encoded value. * * @example * ObjectToStructConverter.convert({ * aString: 'Hi' * }); * // { * // fields: { * // aString: { * // stringValue: 'Hello!' * // } * // } * // } */ convert(obj: {}) { const convertedObject = { fields: {}, }; this.seenObjects.add(obj); for (const prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { const value = obj[prop]; if (is.undefined(value)) { continue; } convertedObject.fields[prop] = this.encodeValue_(value); } } this.seenObjects.delete(obj); return convertedObject; } /** * Convert a raw value to a type-denoted protobuf message-friendly object. * * @private * * @param {*} value - The input value. * @return {*} - The encoded value. * * @example * ObjectToStructConverter.encodeValue('Hi'); * // { * // stringValue: 'Hello!' * // } */ encodeValue_(value: {}) { let convertedValue; if (is.null(value)) { convertedValue = { nullValue: 0, }; } else if (is.number(value)) { convertedValue = { numberValue: value, }; } else if (is.string(value)) { convertedValue = { stringValue: value, }; } else if (is.boolean(value)) { convertedValue = { boolValue: value, }; } else if (Buffer.isBuffer(value)) { convertedValue = { blobValue: value, }; } else if (is.object(value)) { if (this.seenObjects.has(value)) { // Circular reference. if (!this.removeCircular) { throw new Error( [ 'This object contains a circular reference. To automatically', 'remove it, set the `removeCircular` option to true.', ].join(' ') ); } convertedValue = { stringValue: '[Circular]', }; } else { convertedValue = { structValue: this.convert(value), }; } } else if (is.array(value)) { convertedValue = { listValue: { values: (value as Array<{}>).map(this.encodeValue_.bind(this)), }, }; } else { if (!this.stringify) { throw new Error('Value of type ' + typeof value + ' not recognized.'); } convertedValue = { stringValue: String(value), }; } return convertedValue; } } export class GrpcService extends Service { grpc?: typeof grpc; grpcVersion?: string; grpcCredentials?: {}; grpcMetadata?: {add: Function}; maxRetries?: number; userAgent?: string; activeServiceMap_ = new Map(); protos = {}; /** A cache for proto objects. */ private static protoObjectCache: {[name: string]: PackageDefinition} = {}; static readonly GRPC_SERVICE_OPTIONS = GRPC_SERVICE_OPTIONS; static readonly GRPC_ERROR_CODE_TO_HTTP = GRPC_ERROR_CODE_TO_HTTP; static readonly ObjectToStructConverter = ObjectToStructConverter; /** * Service is a base class, meant to be inherited from by a "service," like * BigQuery or Storage. * * This handles making authenticated requests by exposing a `makeReq_` * function. * * @constructor * @alias module:common/grpc-service * * @param config - Configuration object. * @param {object} options - [Configuration object](#/docs/?method=gcloud). */ constructor(config: GrpcServiceConfig, options) { super(config, options); if (global['GCLOUD_SANDBOX_ENV']) { // gRPC has a tendency to cause our doc unit tests to fail, so we prevent // any calls to that library from going through. // Reference: // https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1137#issuecomment-193315047 return global['GCLOUD_SANDBOX_ENV']; } if (config.grpc) { this.grpc = config.grpc; this.grpcVersion = config.grpcVersion || 'grpc/unknown'; } else { this.grpc = grpc; this.grpcVersion = 'grpc/' + new GrpcClient().grpcVersion; } if (config.customEndpoint) { this.grpcCredentials = this.grpc.credentials.createInsecure(); } this.grpcMetadata = new this.grpc.Metadata(); this.grpcMetadata!.add( 'x-goog-api-client', [ 'gl-node/' + process.versions.node, 'gccl/' + config.packageJson.version, this.grpcVersion, ].join(' ') ); if (config.grpcMetadata) { for (const prop in config.grpcMetadata) { this.grpcMetadata!.add(prop, config.grpcMetadata[prop]); } } this.maxRetries = options.maxRetries; this.userAgent = util.getUserAgentFromPackageJson(config.packageJson); this.activeServiceMap_ = new Map(); this.protos = {}; const protoServices = config.protoServices; Object.keys(protoServices).forEach(name => { const protoConfig = protoServices[name]; const services = this.loadProtoFile(protoConfig.path, config); const serviceKey = ['google', protoConfig.service, name] .filter(x => x) .join('.'); const service = services[serviceKey] as ServiceDefinition & { baseUrl?: string; }; this.protos[name] = service; if (protoConfig.baseUrl) { service.baseUrl = protoConfig.baseUrl; } }); } /** * Make an authenticated request with gRPC. * * @param {object} protoOpts - The proto options. * @param {string} protoOpts.service - The service name. * @param {string} protoOpts.method - The method name. * @param {number=} protoOpts.timeout - After how many milliseconds should the * request cancel. * @param {object} reqOpts - The request options. * @param {function=} callback - The callback function. */ request(reqOpts: DecorateRequestOptions): Promise<Response>; request( reqOpts: DecorateRequestOptions, callback: BodyResponseCallback ): void; request( reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback ): void | Promise<Response>; request( protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions, callback: ServiceRequestCallback ): Abortable | void; request( pOpts: ProtoOpts | DecorateRequestOptions, rOpts?: DecorateRequestOptions | BodyResponseCallback, callback?: ServiceRequestCallback ): Abortable | void | Promise<Response> { /** * The function signature above is a little funky. This is due to the way * method overloading in TypeScript operates. Since this class extends * Service, the signatures for `request` need to have * *something* in common. The only signature actually used here is: * * request(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions, callback: * ServiceRequestCallback): Abortable|void; * * Hence the weird casting below. */ const protoOpts = pOpts as ProtoOpts; let reqOpts = rOpts as DecorateRequestOptions; if (global['GCLOUD_SANDBOX_ENV']) { return global['GCLOUD_SANDBOX_ENV']; } if (!this.grpcCredentials) { // We must establish an authClient to give to grpc. this.getGrpcCredentials_((err, credentials) => { if (err) { callback!(err); return; } this.grpcCredentials = credentials; this.request(protoOpts, reqOpts, callback!); }); return; } const service = this.getService_(protoOpts); const metadata = this.grpcMetadata; const grpcOpts: GrpcOptions = {}; if (typeof protoOpts.timeout === 'number') { grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); } try { reqOpts = this.decorateRequest_(reqOpts); } catch (e) { callback!(e); return; } // Retains a reference to an error from the response. If the final callback // is executed with this as the "response", we return it to the user as an // error. let respError; const retryOpts = Object.assign( { retries: this.maxRetries, currentRetryAttempt: 0, shouldRetryFn: GrpcService.shouldRetryRequest_, // retry-request determines if it should retry from the incoming HTTP // response status. gRPC always returns an error proto message. We // pass that "error" into retry-request to act as the HTTP response, // so it can use the status code to determine if it should retry. request(_, onResponse) { respError = null; return service[protoOpts.method]( reqOpts, metadata, grpcOpts, (err, resp) => { if (err) { respError = GrpcService.decorateError_(err); if (respError) { onResponse(null, respError); return; } onResponse(err, resp); return; } onResponse(null, resp); } ); }, }, protoOpts.retryOpts ); return retryRequest(null!, retryOpts, (err, resp: object) => { if (!err && resp === respError) { err = respError; resp = null!; } callback!(err, resp as Response); }); } /** * Make an authenticated streaming request with gRPC. * * @param {object} protoOpts - The proto options. * @param {string} protoOpts.service - The service. * @param {string} protoOpts.method - The method name. * @param {number=} protoOpts.timeout - After how many milliseconds should the * request cancel. * @param {object} reqOpts - The request options. */ requestStream(reqOpts: DecorateRequestOptions): Request; requestStream(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions): Duplex; requestStream( pOpts: ProtoOpts | DecorateRequestOptions, rOpts?: DecorateRequestOptions ): Duplex | Request { /** * The function signature above is a little funky. This is due to the way * method overloading in TypeScript operates. Since this class extends * Service, the signatures for `requestStream` need to have * *something* in common. The only signature actually used here is: * * requestStream(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions): * Duplex; * * Hence the weird casting below. */ if (global['GCLOUD_SANDBOX_ENV']) { return new PassThrough({objectMode: true}); } const protoOpts = pOpts as ProtoOpts; let reqOpts = rOpts as DecorateRequestOptions; if (!protoOpts.stream) { protoOpts.stream = new PassThrough({objectMode: true}); } const stream = protoOpts.stream; if (!this.grpcCredentials) { // We must establish an authClient to give to grpc. this.getGrpcCredentials_((err, credentials) => { if (err) { stream.destroy(err); return; } this.grpcCredentials = credentials; this.requestStream(protoOpts, reqOpts); }); return stream; } const objectMode = !!reqOpts.objectMode; const service = this.getService_(protoOpts); const grpcMetadata = this.grpcMetadata; const grpcOpts: GrpcOptions = {}; if (typeof protoOpts.timeout === 'number') { grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); } try { reqOpts = this.decorateRequest_(reqOpts); } catch (e) { setImmediate(() => { stream.destroy(e); }); return stream; } const retryOpts = Object.assign( { retries: this.maxRetries, currentRetryAttempt: 0, objectMode, shouldRetryFn: GrpcService.shouldRetryRequest_, request() { const ee: EventEmitter = service[protoOpts.method]( reqOpts, grpcMetadata, grpcOpts ).on('metadata', () => { // retry-request requires a server response before it // starts emitting data. The closest mechanism grpc // provides is a metadata event, but this does not provide // any kind of response status. So we're faking it here // with code `0` which translates to HTTP 200. // // https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1444#discussion_r71812636 const grcpStatus = GrpcService.decorateStatus_({code: 0}); ee.emit('response', grcpStatus); }); return ee; }, }, protoOpts.retryOpts ); // eslint-disable-next-line @typescript-eslint/no-explicit-any return (retryRequest(null!, retryOpts) as any) .on('error', err => { const grpcError = GrpcService.decorateError_(err); stream.destroy(grpcError || err); }) .on('request', stream.emit.bind(stream, 'request')) .pipe(stream); } /** * Make an authenticated writable streaming request with gRPC. * * @param {object} protoOpts - The proto options. * @param {string} protoOpts.service - The service. * @param {string} protoOpts.method - The method name. * @param {number=} protoOpts.timeout - After how many milliseconds should the * request cancel. * @param {object} reqOpts - The request options. */ requestWritableStream(protoOpts, reqOpts) { const stream = // eslint-disable-next-line @typescript-eslint/no-explicit-any (protoOpts.stream = protoOpts.stream || (duplexify as any).obj()); if (global['GCLOUD_SANDBOX_ENV']) { return stream; } // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; if (!this.grpcCredentials) { // We must establish an authClient to give to grpc. this.getGrpcCredentials_((err, credentials) => { if (err) { stream.destroy(err); return; } self.grpcCredentials = credentials; self.requestWritableStream(protoOpts, reqOpts); }); return stream; } const service = this.getService_(protoOpts); const grpcMetadata = this.grpcMetadata; const grpcOpts: GrpcOptions = {}; if (is.number(protoOpts.timeout)) { grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); } try { reqOpts = this.decorateRequest_(reqOpts); } catch (e) { setImmediate(() => { stream.destroy(e); }); return stream; } const grpcStream = service[protoOpts.method]( reqOpts, grpcMetadata, grpcOpts ) .on('status', status => { const grcpStatus = GrpcService.decorateStatus_(status); stream.emit('response', grcpStatus || status); }) .on('error', err => { const grpcError = GrpcService.decorateError_(err); stream.destroy(grpcError || err); }); stream.setReadable(grpcStream); stream.setWritable(grpcStream); return stream; } /** * Decode a protobuf Struct's value. * * @param {object} value - A Struct's Field message. * @return {*} - The decoded value. */ static decodeValue_(value) { switch (value.kind) { case 'structValue': { return GrpcService.structToObj_(value.structValue); } case 'nullValue': { return null; } case 'listValue': { return value.listValue.values.map(GrpcService.decodeValue_); } default: { return value[value.kind]; } } } /** * Convert a raw value to a type-denoted protobuf message-friendly object. * * * @param {*} value - The input value. * @return {*} - The encoded value. * * @example * ObjectToStructConverter.encodeValue('Hi'); * // { * // stringValue: 'Hello!' * // } */ static encodeValue_(value) { return new GrpcService.ObjectToStructConverter().encodeValue_(value); } /** * Creates a deadline. * * @private * * @param {number} timeout - Timeout in miliseconds. * @return {date} deadline - The deadline in Date object form. */ private static createDeadline_(timeout: number) { return new Date(Date.now() + timeout); } /** * Checks for a grpc status code and extends the error object with additional * information. * * @private * * @param {error|object} err - The grpc error. * @return {error|null} */ static decorateError_(err: Error): Error | null { const errorObj = is.error(err) ? err : {}; return GrpcService.decorateGrpcResponse_(errorObj, err); } /** * Checks for a grpc status code and extends the supplied object with * additional information. * * @private * * @param {object} obj - The object to be extended. * @param {object} response - The grpc response. * @return {object|null} */ private static decorateGrpcResponse_(obj, response) { if (response && GRPC_ERROR_CODE_TO_HTTP[response.code]) { const defaultResponseDetails = GRPC_ERROR_CODE_TO_HTTP[response.code]; let message = defaultResponseDetails.message; if (response.message) { // gRPC error messages can be either stringified JSON or strings. try { message = JSON.parse(response.message).description; } catch (e) { message = response.message; } } return extend(true, obj, response, { code: defaultResponseDetails.code, message, }); } return null; } /** * Checks for grpc status code and extends the status object with additional * information * * @private * @param {object} status - The grpc status. * @return {object|null} */ private static decorateStatus_(status) { return GrpcService.decorateGrpcResponse_({}, status); } /** * Function to decide whether or not a request retry could occur. * * @private * * @param {object} response - The request response. * @return {boolean} shouldRetry */ private static shouldRetryRequest_(response) { return [429, 500, 502, 503].indexOf(response.code) > -1; } /** * Convert an object to a struct. * * @private * * @param {object} obj - An object to convert. * @param {object=} options - Configuration object. * @param {boolean} options.removeCircular - Remove circular references in the * object with a placeholder string. * @param {boolean} options.stringify - Stringify un-recognized types. * @return {array} - The converted object. * * @example * GrpcService.objToStruct_({ * greeting: 'Hello!', * favNumber: 7, * friendIds: [ * 1004, * 1006 * ], * userDetails: { * termsSigned: true * } * }); * // { * // fields: { * // greeting: { * // stringValue: 'Hello!' * // }, * // favNumber: { * // numberValue: 7 * // }, * // friendIds: { * // listValue: [ * // { * // numberValue: 1004 * // }, * // { * // numberValue: 1006 * // } * // ] * // }, * // userDetails: { * // fields: { * // termsSigned: { * // booleanValue: true * // } * // } * // } * // } * // } */ private static objToStruct_(obj, options) { return new GrpcService.ObjectToStructConverter(options).convert(obj); } /** * Condense a protobuf Struct into an object of only its values. * * @private * * @param {object} struct - A protobuf Struct message. * @return {object} - The simplified object. * * @example * GrpcService.structToObj_({ * fields: { * name: { * kind: 'stringValue', * stringValue: 'Stephen' * } * } * }); * // { * // name: 'Stephen' * // } */ private static structToObj_(struct) { const convertedObject = {}; for (const prop in struct.fields) { const value = struct.fields[prop]; convertedObject[prop] = GrpcService.decodeValue_(value); } return convertedObject; } /** * Assign a projectId if one is specified to all request options. * * @param {object} reqOpts - The request options. * @return {object} - The decorated request object. */ decorateRequest_(reqOpts) { reqOpts = Object.assign({}, reqOpts); delete reqOpts.autoPaginate; delete reqOpts.autoPaginateVal; delete reqOpts.objectMode; return replaceProjectIdToken(reqOpts, this.projectId); } /** * To authorize requests through gRPC, we must get the raw google-auth-library * auth client object. * * @private * * @param {function} callback - The callback function. * @param {?error} callback.err - An error getting an auth client. */ private getGrpcCredentials_(callback) { this.authClient.getClient().then(client => { const credentials = this.grpc!.credentials.combineChannelCredentials( this.grpc!.credentials.createSsl(), this.grpc!.credentials.createFromGoogleCredential(client) ); if (!this.projectId || this.projectId === '{{projectId}}') { this.projectId = client.projectId!; } callback(null, credentials); }, callback); } /** * Loads a proto file, useful when handling multiple proto files/services * within a single instance of GrpcService. * * @private * * @param protoConfig - The proto specific configs for this file. * @param config - The base config for the GrpcService. * @return protoObject - The loaded proto object. */ private loadProtoFile( protoPath: string, config: GrpcServiceConfig ): PackageDefinition { const protoObjectCacheKey = [config.protosDir, protoPath].join('$'); if (!GrpcService.protoObjectCache[protoObjectCacheKey]) { const services = loadSync(protoPath, { keepCase: false, defaults: true, bytes: String, longs: String, enums: String, oneofs: true, includeDirs: [config.protosDir, gaxProtoPath], }); GrpcService.protoObjectCache[protoObjectCacheKey] = services; } return GrpcService.protoObjectCache[protoObjectCacheKey]; } /** * Retrieves the service object used to make the grpc requests. * * @private * * @param {object} protoOpts - The proto options. * @return {object} service - The proto service. */ private getService_(protoOpts) { const proto = this.protos[protoOpts.service]; let service = this.activeServiceMap_.get(protoOpts.service); if (!service) { service = new proto[protoOpts.service]( proto.baseUrl || this.baseUrl, this.grpcCredentials, Object.assign( { 'grpc.primary_user_agent': this.userAgent, }, GRPC_SERVICE_OPTIONS ) ); this.activeServiceMap_.set(protoOpts.service, service); } return service; } }
the_stack
import DataProxyImpl from "platform-components/connection/dataProxy"; import CommunicationsManager, {CommunicationsManagerListener} from "./communicationsManager"; import ClientComm5 from "./comm5/clientComm5"; import DataProxy from "./dataProxy"; import {Conversation, ConversationItem, LinkedConversation, MessageModifier} from "../data/blocks"; import { AttachmentRequestErrorCode, ConnectionErrorCode, CreateChatErrorCode, FaceTimeInitiateCode, FaceTimeLinkErrorCode, MessageError, MessageErrorCode, RemoteUpdateErrorCode } from "../data/stateCodes"; import EventEmitter, {CachedEventEmitter} from "../util/eventEmitter"; import ProgressPromise from "../util/progressPromise"; import promiseTimeout from "../util/promiseTimeout"; import {TransferAccumulator} from "./transferAccumulator"; import {isCryptoPasswordSet, setCryptoPassword} from "shared/util/encryptionUtils"; import {getSecureLS, SecureStorageKey} from "shared/util/secureStorageUtils"; import FileDownloadResult from "shared/data/fileDownloadResult"; import ServerUpdateData from "shared/data/serverUpdateData"; import ResolveablePromiseTimeout from "shared/util/resolveablePromiseTimeout"; import CallEvent from "shared/data/callEvent"; import ConversationTarget from "shared/data/conversationTarget"; export const warnCommVer: number[] = [5, 4]; //Warn users on a communications version older than this to update export const targetCommVer: number[] = [5, 5]; export const targetCommVerString = targetCommVer.join("."); //How often to try reconnecting when disconnected const reconnectInterval = 8 * 1000; const requestTimeoutMillis = 10 * 1000; type ConnectionState = "disconnected" | "connecting" | "connected"; //Server information let _serverSystemVersion: string | undefined; export function getServerSystemVersion(): string | undefined { return _serverSystemVersion; } let _serverSoftwareVersion: string | undefined; export function getServerSoftwareVersion(): string | undefined { return _serverSoftwareVersion; } let _serverComputerName: string | undefined; export function getServerComputerName(): string | undefined { return _serverComputerName; } //Communications manager constructor shape interface CreatesCommunicationsManager { new(dataProxy: DataProxy): CommunicationsManager } //Connection values const communicationsPriorityList: ReadonlyArray<CreatesCommunicationsManager> = [ClientComm5]; let reconnectTimeoutID: any | undefined; let communicationsManager: CommunicationsManager | null = null; let dataProxy: DataProxy = new DataProxyImpl(); export function setDataProxy(value: DataProxy) { dataProxy = value; } //Config values let disableAutomaticReconnections = false; export function setDisableAutomaticReconnections(value: boolean) { disableAutomaticReconnections = value; } //Listener values export interface ConnectionListener { onConnecting: () => void; onOpen: () => void; onClose: (reason: ConnectionErrorCode) => void; } const connectionListenerArray: ConnectionListener[] = []; export interface RemoteUpdateListener { onUpdate?: (update: ServerUpdateData | undefined) => void; onInitiate?: () => void; onError?: (code: RemoteUpdateErrorCode, details?: string) => void; } const remoteUpdateListenerArray: RemoteUpdateListener[] = []; //Promise response values interface PromiseExecutor<T> { resolve: (value: T | PromiseLike<T>) => void; reject: (reason?: any) => void; } interface ProgressPromiseExecutor<T, P> { resolve: (value: T | PromiseLike<T>) => void; reject: (reason?: any) => void; progress: (progress: P) => void; } const liteConversationPromiseArray: PromiseExecutor<LinkedConversation[]>[] = []; //Retrieval of all lite conversations interface ThreadKey { chatGUID: string; firstMessageID?: number; } const conversationDetailsPromiseMap: Map<string, PromiseExecutor<[string, Conversation | undefined][]>[]> = new Map(); //Retrieval of a specific conversation's details const threadPromiseMap: Map<string, PromiseExecutor<ConversationItem[]>[]> = new Map(); //Retrieval of messages from a thread let faceTimeLinkPromise: ResolveablePromiseTimeout<string> | undefined = undefined; //Creating a FaceTime link let faceTimeInitiatePromise: ResolveablePromiseTimeout<void> | undefined = undefined; //Initiating a FaceTime call class FileDownloadState { private accumulator?: TransferAccumulator; public get accumulatedData() { return this.accumulator!.data; } public get accumulatedDataOffset() { return this.accumulator!.offset; } promise: ProgressPromiseExecutor<FileDownloadResult, FileDownloadProgress>; private readonly timeoutCallback: () => void; private timeoutID: any | undefined; public downloadFileName: string | undefined = undefined; public downloadFileType: string | undefined = undefined; constructor(promise: ProgressPromiseExecutor<FileDownloadResult, FileDownloadProgress>, timeoutCallback: () => void) { this.promise = promise; this.timeoutCallback = timeoutCallback; } public initializeAccumulator(accumulator: TransferAccumulator) { //Setting the accumulator this.accumulator = accumulator; this.refreshTimeout(); } public appendData(data: ArrayBuffer) { //Adding the data to the array this.accumulator!.push(data); this.refreshTimeout(); } public finish() { if(this.timeoutID) clearTimeout(this.timeoutID); } private refreshTimeout() { if(this.timeoutID) clearTimeout(this.timeoutID); this.timeoutID = setTimeout(this.timeoutCallback, requestTimeoutMillis); } } interface FileDownloadProgress { type: "size" | "downloaded"; value: number; } const fileDownloadStateMap: Map<number, FileDownloadState> = new Map(); //Attachment data retrieval const messageSendPromiseMap: Map<number, PromiseExecutor<any>> = new Map(); //Response from sending a message const chatCreatePromiseMap: Map<number, PromiseExecutor<string>> = new Map(); //Response from creating a chat export const messageUpdateEmitter = new EventEmitter<ConversationItem[]>(); //Message updates export const modifierUpdateEmitter = new EventEmitter<MessageModifier[]>(); //Modifier updates export const faceTimeSupportedEmitter = new CachedEventEmitter<boolean>(false); //Whether the connected server supports FaceTime export const incomingCallerEmitter = new CachedEventEmitter<string | undefined>(); //The current incoming caller export const outgoingCalleeEmitter = new CachedEventEmitter<string[] | undefined>(); //The current outgoing callee export const callEventEmitter = new EventEmitter<CallEvent>(); //Standard call events //Common promise responses const messageErrorNetwork: MessageError = {code: MessageErrorCode.LocalNetwork}; //State values let connState: ConnectionState = "disconnected"; let isConnectingPassively = false; let lastServerMessageID: number | undefined = undefined; let lastConnectionUpdateTime: Date | undefined = undefined; //The last time the client received a message from the server let nextRequestID: number = 0; function onOnline() { //Reconnecting connect(); } function onOffline() { //Disconnecting disconnect(); } const communicationsManagerListener: CommunicationsManagerListener = { onOpen(computerName: string, systemVersion: string, softwareVersion: string, supportsFaceTime: boolean): void { //Updating the state updateStateConnected(); //Recording the server information _serverComputerName = computerName; _serverSystemVersion = systemVersion; _serverSoftwareVersion = softwareVersion; faceTimeSupportedEmitter.notify(supportsFaceTime); //Listening for network events window.addEventListener("online", onOnline); window.addEventListener("offline", onOffline); }, onClose(reason: ConnectionErrorCode): void { //Failing all pending promises rejectAndClear(liteConversationPromiseArray, messageErrorNetwork); rejectAndClear(conversationDetailsPromiseMap, messageErrorNetwork); rejectAndClear(threadPromiseMap, messageErrorNetwork); for(const state of fileDownloadStateMap.values()) state.promise.reject(AttachmentRequestErrorCode.Timeout); fileDownloadStateMap.clear(); for(const promise of messageSendPromiseMap.values()) promise.reject(messageErrorNetwork); messageSendPromiseMap.clear(); for(const promise of chatCreatePromiseMap.values()) promise.reject([CreateChatErrorCode.Network, undefined]); chatCreatePromiseMap.clear(); faceTimeLinkPromise?.reject(FaceTimeLinkErrorCode.Network); faceTimeLinkPromise = undefined; faceTimeInitiatePromise?.reject(FaceTimeInitiateCode.Network); faceTimeInitiatePromise = undefined; //Updating the state updateStateDisconnected(reason); incomingCallerEmitter.notify(undefined); outgoingCalleeEmitter.notify(undefined); for(const listener of remoteUpdateListenerArray) listener.onUpdate?.(undefined); //Checking if the error is automatically recoverable if((reason === ConnectionErrorCode.Connection || reason === ConnectionErrorCode.Internet) && !disableAutomaticReconnections) { //Scheduling a passive reconnection reconnectTimeoutID = setTimeout(() => { if(!disableAutomaticReconnections) { connectPassive(); } }, reconnectInterval); } //Removing the network event listeners window.removeEventListener("online", onOnline); window.removeEventListener("offline", onOffline); }, onPacket(): void { if(connState === "connected") { //Recording the last connection update time lastConnectionUpdateTime = new Date(); } }, onMessageUpdate(data: ConversationItem[]): void { //Notifying the listeners messageUpdateEmitter.notify(data); }, onConversationUpdate(data: [string, Conversation | undefined][]): void { //Resolving pending promises const promiseMapKey = data.map(data => data[0]).join(" "); const promiseArray = conversationDetailsPromiseMap.get(promiseMapKey); if(promiseArray) { for(const promise of promiseArray) promise.resolve(data); threadPromiseMap.delete(promiseMapKey); } }, onModifierUpdate(data: MessageModifier[]): void { //Notifying the listeners modifierUpdateEmitter.notify(data); }, onFileRequestStart(requestID, downloadFileName, downloadFileType, dataLength, accumulator) { //Finding the local request const state = fileDownloadStateMap.get(requestID); if(!state) return; //Setting the download file information state.downloadFileName = downloadFileName; state.downloadFileType = downloadFileType; //Setting the accumulator state.initializeAccumulator(accumulator); //Updating the progress state.promise.progress({type: "size", value: dataLength}); }, onFileRequestData(requestID: number, data: ArrayBuffer): void { //Finding the local request const state = fileDownloadStateMap.get(requestID); if(!state) return; //Adding the data state.appendData(data); //Updating the progress state.promise.progress({type: "downloaded", value: state.accumulatedDataOffset}); }, onFileRequestComplete(requestID: number): void { //Finding the local request const state = fileDownloadStateMap.get(requestID); if(!state) return; //Finishing the request state.finish(); state.promise.resolve({ data: state.accumulatedData, downloadName: state.downloadFileName, downloadType: state.downloadFileType, }); //Removing the request fileDownloadStateMap.delete(requestID); }, onFileRequestFail(requestID: number, error: AttachmentRequestErrorCode): void { //Finding the local request const state = fileDownloadStateMap.get(requestID); if(!state) return; //Failing the request state.promise.reject(error); //Removing the request fileDownloadStateMap.delete(requestID); }, onIDUpdate(messageID: number): void { //Recording the last message ID lastServerMessageID = messageID; }, onMessageConversations(data: LinkedConversation[]): void { //Resolving pending promises for(const promise of liteConversationPromiseArray) promise.resolve(data); //Emptying the array liteConversationPromiseArray.length = 0; }, onMessageThread(chatGUID: string, firstMessageID: number | undefined, data: ConversationItem[]) { //Resolving pending promises const promiseMapKey = JSON.stringify({chatGUID: chatGUID, firstMessageID: firstMessageID} as ThreadKey); const promiseArray = threadPromiseMap.get(promiseMapKey); if(promiseArray) { for(const promise of promiseArray) promise.resolve(data); threadPromiseMap.delete(promiseMapKey); } }, onSendMessageResponse(requestID: number, error: MessageError | undefined): void { //Resolving pending promises const promise = messageSendPromiseMap.get(requestID); if(!promise) return; if(error) promise.reject(error); else promise.resolve(undefined); chatCreatePromiseMap.delete(requestID); }, onCreateChatResponse(requestID: number, error: CreateChatErrorCode | undefined, details: string | undefined): void { //Resolving pending promises const promise = chatCreatePromiseMap.get(requestID); if(!promise) return; if(error === undefined) { if(details) { promise.resolve(details); } else { promise.reject([CreateChatErrorCode.Network, undefined]); } } else { promise.reject([error, details]); } chatCreatePromiseMap.delete(requestID); }, onSoftwareUpdateListing(updateData: ServerUpdateData | undefined): void { for(const listener of remoteUpdateListenerArray) listener.onUpdate?.(updateData); }, onSoftwareUpdateInstall(installing: boolean): void { if(installing) { for(const listener of remoteUpdateListenerArray) listener.onInitiate?.(); } else { for(const listener of remoteUpdateListenerArray) listener.onError?.(RemoteUpdateErrorCode.Mismatch); } }, onSoftwareUpdateError(error: RemoteUpdateErrorCode, details: string | undefined): void { for(const listener of remoteUpdateListenerArray) listener.onError?.(error, details); }, onFaceTimeNewLink(faceTimeLink: string | undefined): void { //Ignoring if there is no pending request if(faceTimeLinkPromise === undefined) return; //Resolving the completable if(faceTimeLink === undefined) { faceTimeLinkPromise.reject(FaceTimeLinkErrorCode.External); } else { faceTimeLinkPromise.resolve(faceTimeLink); } faceTimeLinkPromise = undefined; }, onFaceTimeOutgoingCallInitiated(resultCode: FaceTimeInitiateCode, errorDetails: string | undefined): void { //Ignoring if there is no pending request if(faceTimeInitiatePromise === undefined) return; //Resolving the completable if(resultCode === FaceTimeInitiateCode.OK) { faceTimeInitiatePromise.resolve(); } else { faceTimeInitiatePromise.reject([resultCode, errorDetails]); } faceTimeInitiatePromise = undefined; }, onFaceTimeOutgoingCallAccepted(faceTimeLink: string): void { callEventEmitter.notify({type: "outgoingAccepted", faceTimeLink}); outgoingCalleeEmitter.notify(undefined); }, onFaceTimeOutgoingCallRejected(): void { callEventEmitter.notify({type: "outgoingRejected"}); outgoingCalleeEmitter.notify(undefined); }, onFaceTimeOutgoingCallError(errorDetails: string | undefined): void { callEventEmitter.notify({type: "outgoingError", errorDetails}); outgoingCalleeEmitter.notify(undefined); }, onFaceTimeIncomingCall(caller: string | undefined): void { incomingCallerEmitter.notify(caller); }, onFaceTimeIncomingCallHandled(faceTimeLink: string): void { callEventEmitter.notify({type: "incomingHandled", faceTimeLink}); }, onFaceTimeIncomingCallError(errorDetails: string | undefined): void { callEventEmitter.notify({type: "incomingHandleError", errorDetails}); } }; function updateStateDisconnected(reason: ConnectionErrorCode) { connState = "disconnected"; for(const listener of connectionListenerArray) listener.onClose(reason); } function updateStateConnecting() { connState = "connecting"; for(const listener of connectionListenerArray) listener.onConnecting(); } function updateStateConnected() { connState = "connected"; for(const listener of connectionListenerArray) listener.onOpen(); } function generateRequestID(): number { //Recording the next request ID const requestID = nextRequestID; //Increasing the request ID (and overflowing at Java's max short value) if(nextRequestID === 32767) nextRequestID = -32768; else nextRequestID++; //Returning the request ID return requestID; } export async function connect() { //Load the password if it hasn't been loaded yet if(!isCryptoPasswordSet()) { try { await setCryptoPassword(await getSecureLS(SecureStorageKey.ServerPassword)); } catch(error) { console.warn(error); } } //Checking if a passive reconnection is in progress if(isConnectingPassively) { //Bringing the state from passive to the foreground updateStateConnecting(); isConnectingPassively = false; return; } //Cancelling the reconnect timeout if it's running if(reconnectTimeoutID) { clearTimeout(reconnectTimeoutID); reconnectTimeoutID = undefined; } //Setting the state to connecting updateStateConnecting(); //Connecting from the top of the priority list connectFromList(0); } function connectPassive() { //Recording the state isConnectingPassively = true; //Clearing the timeout ID (this function can only be called when the timer expires) reconnectTimeoutID = undefined; //Connecting from the top of the priority list connectFromList(0); } function connectFromList(index: number) { communicationsManager = new communicationsPriorityList[index](dataProxy); communicationsManager.listener = communicationsManagerListener; communicationsManager.connect(); } export function disconnect() { communicationsManager?.disconnect(ConnectionErrorCode.Internet); } export function isConnected(): boolean { return connState === "connected"; } export function isDisconnected(): boolean { return connState === "disconnected"; } function requestTimeoutMap<T, K>(key: K, map: Map<K, any>, timeoutReason: any | undefined = messageErrorNetwork, promise: Promise<T>): Promise<T> { const timedPromise = promiseTimeout(requestTimeoutMillis, timeoutReason, promise); timedPromise.catch(() => map.delete(key)); //Remove the promise from the map on error return timedPromise; } function requestTimeoutArray<T, K>(array: K[], timeoutReason: any | undefined = messageErrorNetwork, promise: Promise<T>): Promise<T> { const timedPromise = promiseTimeout(requestTimeoutMillis, timeoutReason, promise); timedPromise.catch(() => array.length = 0); //Clear the array on error return timedPromise; } export function sendMessage(target: ConversationTarget, message: string): Promise<any> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject(messageErrorNetwork); //Starting a new promise const requestID = generateRequestID(); return requestTimeoutMap(requestID, messageSendPromiseMap, undefined, new Promise<any>((resolve, reject) => { //Sending the request communicationsManager!.sendMessage(requestID, target, message); //Recording the promise messageSendPromiseMap.set(requestID, {resolve: resolve, reject: reject}); })); } export function sendFile(chatGUID: ConversationTarget, file: File): ProgressPromise<any, string | number> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject(messageErrorNetwork) as ProgressPromise<any, string | number>; //Starting a new promise return new ProgressPromise<any, string | number>((resolve, reject, progress) => { const requestID = generateRequestID(); //Sending the request communicationsManager!.sendFile(requestID, chatGUID, file, progress) .then((value) => { //Forwarding the value to the promise progress(value); //Starting a timeout for the server response setTimeout(reject, requestTimeoutMillis); }) .catch((error) => { //Forwarding the value to the promise reject(error); //Removing this promise from the map messageSendPromiseMap.delete(requestID); }); //Recording the promise messageSendPromiseMap.set(requestID, {resolve: resolve, reject: reject}); }); } export function fetchConversations(): Promise<LinkedConversation[]> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject(messageErrorNetwork); //Starting a new promise return requestTimeoutArray(liteConversationPromiseArray, undefined, new Promise<LinkedConversation[]>((resolve, reject) => { //Sending the request communicationsManager!.requestLiteConversations(); //Recording the promise liteConversationPromiseArray.push({resolve: resolve, reject: reject}); })); } export function fetchConversationInfo(chatGUIDs: string[]): Promise<[string, LinkedConversation | undefined][]> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject(messageErrorNetwork); //Starting a new promise const key = chatGUIDs.join(" "); return requestTimeoutMap(key, conversationDetailsPromiseMap, undefined, new Promise<[string, LinkedConversation | undefined][]>((resolve, reject) => { //Sending the request communicationsManager!.requestConversationInfo(chatGUIDs); //Recording the promise pushKeyedArray(conversationDetailsPromiseMap, key, {resolve: resolve, reject: reject}); })); } export function fetchThread(chatGUID: string, firstMessageID?: number): Promise<ConversationItem[]> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject(messageErrorNetwork); //Starting a new promise const key = JSON.stringify({chatGUID: chatGUID, firstMessageID: firstMessageID} as ThreadKey); return requestTimeoutMap(key, threadPromiseMap, undefined, new Promise<ConversationItem[]>((resolve, reject) => { //Sending the request communicationsManager!.requestLiteThread(chatGUID, firstMessageID); //Recording the promise pushKeyedArray(threadPromiseMap, key, {resolve: resolve, reject: reject}); })); } export function fetchAttachment(attachmentGUID: string): ProgressPromise<FileDownloadResult, FileDownloadProgress> { //Failing immediately if there is no network connection if(!isConnected()) return ProgressPromise.reject(AttachmentRequestErrorCode.Timeout) as ProgressPromise<FileDownloadResult, FileDownloadProgress>; //Starting a new promise return new ProgressPromise<FileDownloadResult, FileDownloadProgress>((resolve, reject, progress) => { const requestID = generateRequestID(); //Sending the request communicationsManager!.requestAttachmentDownload(requestID, attachmentGUID); //Recording the promise fileDownloadStateMap.set(requestID, new FileDownloadState({resolve: resolve, reject: reject, progress: progress}, () => { //Removing and rejecting the promise fileDownloadStateMap.delete(requestID); reject(); })); }); } export function createChat(members: string[], service: string): Promise<string> { //Failing immediately if there is no network connection if(!isConnected()) return Promise.reject([CreateChatErrorCode.Network, undefined]); //Starting a new promise const requestID = generateRequestID(); return requestTimeoutMap(requestID, chatCreatePromiseMap, [CreateChatErrorCode.Network, undefined], new Promise<string>((resolve, reject) => { //Sending the request communicationsManager!.requestChatCreation(requestID, members, service); //Recording the promise chatCreatePromiseMap.set(requestID, {resolve: resolve, reject: reject}); })); } export function requestMissedMessages() { if(lastServerMessageID !== undefined && lastConnectionUpdateTime !== undefined) { communicationsManager!.requestRetrievalID(lastServerMessageID, lastConnectionUpdateTime, new Date()); } else if(lastConnectionUpdateTime !== undefined) { communicationsManager!.requestRetrievalTime(lastConnectionUpdateTime, new Date()); } else { console.warn("Trying to fetch missed messages with no last connection update time!"); } } export function installRemoteUpdate(updateID: number): void { //Failing immediately if there is no network connection if(!isConnected()) return; //Sending the request communicationsManager!.requestInstallRemoteUpdate(updateID); } /** * Requests a FaceTime link from the server * @return A promise that resolves with the fetched FaceTime link */ export function requestFaceTimeLink(): Promise<string> { //If there is already an active request, return it if(faceTimeLinkPromise !== undefined) { return faceTimeLinkPromise.promise; } //Failing immediately if there is no network connection if(!isConnected()) { return Promise.reject(FaceTimeLinkErrorCode.Network); } //Creating the promise faceTimeLinkPromise = new ResolveablePromiseTimeout(); //Setting a timeout faceTimeLinkPromise.timeout(requestTimeoutMillis, FaceTimeLinkErrorCode.Network); //Starting the request communicationsManager!.requestFaceTimeLink(); //Returning the promise return faceTimeLinkPromise.promise; } /** * Initiates a new outgoing FaceTime call with the specified addresses * @param addresses The list of addresses to initiate the call with * @return A promise that resolves when the call is initiated */ export function initiateFaceTimeCall(addresses: string[]): Promise<void> { //If there is already an active request, return it if(faceTimeInitiatePromise !== undefined) { return faceTimeInitiatePromise.promise; } //Failing immediately if there is no network connection if(!isConnected()) { return Promise.reject([FaceTimeInitiateCode.Network, undefined]); } //Creating the promise faceTimeInitiatePromise = new ResolveablePromiseTimeout(); //Setting a timeout faceTimeInitiatePromise.timeout(requestTimeoutMillis, [FaceTimeInitiateCode.Network, undefined]); //Starting the request communicationsManager!.initiateFaceTimeCall(addresses); //Emitting an update outgoingCalleeEmitter.notify(addresses); faceTimeInitiatePromise.promise.catch(() => { outgoingCalleeEmitter.notify(undefined); }); //Returning the promise return faceTimeInitiatePromise.promise; } /** * Accepts or rejects a pending incoming FaceTime call * @param caller The name of the caller to accept or reject the call of * @param accept True to accept the call, or false to reject * @return Whether the request was successfully sent */ export function handleIncomingFaceTimeCall(caller: string, accept: boolean): void { //Failing immediately if there is no network connection if(!isConnected()) return; //Sending the request communicationsManager!.handleIncomingFaceTimeCall(caller, accept); } /** * Tells the server to leave the current FaceTime call */ export function dropFaceTimeCallServer(): void { //Failing immediately if there is no network connection if(!isConnected()) return; //Sending the request communicationsManager!.dropFaceTimeCallServer(); } export function addConnectionListener(listener: ConnectionListener) { connectionListenerArray.push(listener); } export function removeConnectionListener(listener: ConnectionListener) { const index = connectionListenerArray.indexOf(listener, 0); if(index > -1) connectionListenerArray.splice(index, 1); } export function addRemoteUpdateListener(listener: RemoteUpdateListener) { remoteUpdateListenerArray.push(listener); } export function removeRemoteUpdateListener(listener: RemoteUpdateListener) { const index = remoteUpdateListenerArray.indexOf(listener, 0); if(index > -1) remoteUpdateListenerArray.splice(index, 1); } export function getActiveCommVer(): number[] | undefined { return communicationsManager?.communicationsVersion; } export function getActiveProxyType(): string { return dataProxy.proxyType; } function pushKeyedArray<K, R>(map: Map<K, R[]>, key: K, value: R): void { //Finding the array in the map const array = map.get(key); //Pushing the value directly to the array if it exists if(array) array.push(value); //Otherwise, create a new array with the value else map.set(key, [value]); } function rejectAndClear(items: PromiseExecutor<any>[], reason?: any): void; function rejectAndClear(items: Map<any, PromiseExecutor<any>[]>, reason?: any): void; function rejectAndClear(items: PromiseExecutor<any>[] | Map<any, PromiseExecutor<any>[]>, reason?: any): void { if(items instanceof Array) { for(const promise of items) promise.reject(reason); items.length = 0; } else if(items instanceof Map) { for(const promiseArray of items.values()) { for(const promise of promiseArray) { promise.reject(reason); } } items.clear(); } }
the_stack
import type { SqliteSqlBuilder } from "../sqlBuilders/SqliteSqlBuilder" import type { QueryRunner } from "../queryRunners/QueryRunner" import type { Sqlite, TypeSafeDB, TypeUnsafeDB } from "../databases" import type { SqliteDateTimeFormat, SqliteDateTimeFormatType } from "./SqliteConfiguration" import { AbstractConnection } from "./AbstractConnection" export abstract class AbstractSqliteConnection<DB extends Sqlite & (TypeUnsafeDB | TypeSafeDB)> extends AbstractConnection<DB> { constructor(queryRunner: QueryRunner, sqlBuilder: SqliteSqlBuilder) { super(queryRunner, sqlBuilder) queryRunner.useDatabase('sqlite') } /** * The compatibility mode avoid to use the newer syntax introduces in the newer versions of sqlite * * The newer syntax are: * - Sqlite 3.30.0 (2019-10-04): Add support for the NULLS FIRST and NULLS LAST syntax in ORDER BY clauses. * In the copatibility mode their are emulated * - Sqlite 3.35.0 (2021-03-12): Add support for the RETURNING clause on DELETE, INSERT, and UPDATE statements. * In the compatibility mode last_insert_id() is used to get the last inserted id. * When the compatibility mode is disabled the RETURNING clause on the insert statement is used. */ protected compatibilityMode: boolean = true protected getDateTimeFormat(_type: SqliteDateTimeFormatType): SqliteDateTimeFormat { return 'localdate as text' } protected treatUnexpectedIntegerDateTimeAsJulian: boolean = false protected treatUnexpectedStringDateTimeAsUTC: boolean = false protected unexpectedUnixDateTimeAreMilliseconds: boolean = false protected transformValueFromDB(value: unknown, type: string): unknown { if (value === undefined || value == null) { return super.transformValueFromDB(value, type) } switch (type) { case 'localDate': { if (typeof value === 'string') { const valueAsNumber = +value if (!isNaN(valueAsNumber)) { value = valueAsNumber } } const dateTimeFormat = this.getDateTimeFormat('date') let result: Date if (value instanceof Date) { result = new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate())) } else if (typeof value === 'string') { if (containsTimezone(value)) { result = new Date(value) } else switch (dateTimeFormat) { case 'localdate as text': case 'localdate as text using T separator': if (value.length <= 10) { result = new Date(value + ' 00:00') // If time is omited, UTC timezone will be used instead the local one } else { result = new Date(value) } result = new Date(Date.UTC(result.getFullYear(), result.getMonth(), result.getDate())) break case 'Julian day as real number': case 'Unix time seconds as integer': case 'Unix time milliseconds as integer': if (!this.treatUnexpectedStringDateTimeAsUTC) { if (value.length <= 10) { result = new Date(value + ' 00:00') // If time is omited, UTC timezone will be used instead the local one } else { result = new Date(value) } result = new Date(Date.UTC(result.getFullYear(), result.getMonth(), result.getDate())) } else { result = new Date(value + 'Z') } break case 'UTC as text': case 'UTC as text using T separator': case 'UTC as text using Z timezone': case 'UTC as text using T separator and Z timezone': result = new Date(value + 'Z') break default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } else if (typeof value === 'number' || typeof value === 'bigint') { let number: number = (typeof value === 'bigint') ? Number(value) : value; if (dateTimeFormat === 'Julian day as real number') { result = new Date(julianToMilliseconds(number)) // Timezone is not compesated due down time is overwrited } else if (dateTimeFormat === 'Unix time seconds as integer') { result = new Date(number * 1000) } else if (dateTimeFormat === 'Unix time milliseconds as integer') { result = new Date(number) } else { // Try to automatically detect if it is a julian or a unix time // If it have decimal, it will be considered julian, otherwise unix time if (this.treatUnexpectedIntegerDateTimeAsJulian || !Number.isInteger(value)) { result = new Date(julianToMilliseconds(number)) } else if (this.unexpectedUnixDateTimeAreMilliseconds) { result = new Date(number) } else { result = new Date(number * 1000) } } result.setUTCHours(0, 0, 0, 0) } else { throw new Error(`Invalid localDate value received from the db: ${value} (type ${typeof value})`) } if (isNaN(result.getTime())) { throw new Error(`Invalid localDate value received from the db: ${value} (.getTime() returns NaN)`) } (result as any).___type___ = 'localDate' // This time fix works in almost every timezone (from -10 to +13, but not +14, -11, -12, almost uninhabited) result.setUTCMinutes(600) return result } case 'localTime': { if (typeof value === 'string') { const valueAsNumber = +value if (!isNaN(valueAsNumber)) { value = valueAsNumber } } const dateTimeFormat = this.getDateTimeFormat('time') let result: Date if (value instanceof Date) { result = new Date(value.getTime()) } else if (typeof value === 'string') { if (containsTimezone(value)) { if (containsDate(value)) { result = new Date(value) } else { result = new Date('1970-01-01 ' + value) } } else switch (dateTimeFormat) { case 'localdate as text': case 'localdate as text using T separator': if (containsDate(value)) { result = new Date(value) } else { result = new Date('1970-01-01 ' + value) } break case 'Julian day as real number': case 'Unix time seconds as integer': case 'Unix time milliseconds as integer': if (containsDate(value)) { if (this.treatUnexpectedStringDateTimeAsUTC) { result = new Date(value + 'Z') } else { result = new Date(value) } } else { if (this.treatUnexpectedStringDateTimeAsUTC) { result = new Date('1970-01-01 ' + value + 'Z') } else { result = new Date('1970-01-01 ' + value) } } break case 'UTC as text': case 'UTC as text using T separator': case 'UTC as text using Z timezone': case 'UTC as text using T separator and Z timezone': if (containsDate(value)) { result = new Date(value + 'Z') } else { result = new Date('1970-01-01 ' + value + 'Z') } break default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } else if (typeof value === 'number' || typeof value === 'bigint') { let number: number = (typeof value === 'bigint') ? Number(value) : value; if (dateTimeFormat === 'Julian day as real number') { result = new Date(julianToMilliseconds(number + 2440587.5 /* 1970-01-01 */)) } else if (dateTimeFormat === 'Unix time seconds as integer') { result = new Date(number * 1000) } else if (dateTimeFormat === 'Unix time milliseconds as integer') { result = new Date(number) } else { // Try to automatically detect if it is a julian or a unix time // If it have decimal, it will be considered julian, otherwise unix time if (this.treatUnexpectedIntegerDateTimeAsJulian || !Number.isInteger(number)) { if (number >= -1 && number <= 1) { result = new Date(julianToMilliseconds(number + 2440587.5 /* 1970-01-01 */)) } else { result = new Date(julianToMilliseconds(number)) } } else if (this.unexpectedUnixDateTimeAreMilliseconds) { result = new Date(number) } else { result = new Date(number * 1000) } } } else { throw new Error(`Invalid localTime value received from the db: ${value} (type ${typeof value})`) } if (isNaN(result.getTime())) { throw new Error(`Invalid localTime value received from the db: ${value} (.getTime() returns NaN)`) } (result as any).___type___ = 'localTime' result.setFullYear(1970, 0, 1) return result } case 'localDateTime': { if (typeof value === 'string') { const valueAsNumber = +value if (!isNaN(valueAsNumber)) { value = valueAsNumber } } const dateTimeFormat = this.getDateTimeFormat('dateTime') let result: Date if (value instanceof Date) { result = value } else if (typeof value === 'string') { if (containsTimezone(value)) { result = new Date(value) } else switch (dateTimeFormat) { case 'localdate as text': case 'localdate as text using T separator': result = new Date(value) break case 'Julian day as real number': case 'Unix time seconds as integer': if (this.treatUnexpectedStringDateTimeAsUTC) { result = new Date(value + 'Z') } else { result = new Date(value) } break case 'UTC as text': case 'UTC as text using T separator': case 'UTC as text using Z timezone': case 'UTC as text using T separator and Z timezone': result = new Date(value + 'Z') break default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } else if (typeof value === 'number' || typeof value === 'bigint') { let number: number = (typeof value === 'bigint') ? Number(value) : value; if (dateTimeFormat === 'Julian day as real number') { result = new Date(julianToMilliseconds(number)) // Timezone is not compesated due down time is overwrited } else if (dateTimeFormat === 'Unix time seconds as integer') { result = new Date(number * 1000) } else if (dateTimeFormat === 'Unix time milliseconds as integer') { result = new Date(number) } else { // Try to automatically detect if it is a julian or a unix time // If it have decimal, it will be considered julian, otherwise unix time if (this.treatUnexpectedIntegerDateTimeAsJulian || !Number.isInteger(value)) { result = new Date(julianToMilliseconds(number)) } else if (this.unexpectedUnixDateTimeAreMilliseconds) { result = new Date(number) } else { result = new Date(number * 1000) } } } else { throw new Error(`Invalid localDateTime value received from the db: ${value} (type ${typeof value})`) } if (isNaN(result.getTime())) { throw new Error(`Invalid localDateTime value received from the db: ${value} (.getTime() returns NaN)`) } (result as any).___type___ = 'LocalDateTime' return result } } return super.transformValueFromDB(value, type) } protected transformValueToDB(value: unknown, type: string): unknown { if (value === undefined || value == null) { return super.transformValueToDB(value, type) } switch (type) { case 'localDate': if (value instanceof Date && !isNaN(value.getTime())) { const dateTimeFormat = this.getDateTimeFormat('date') switch (dateTimeFormat) { case 'localdate as text': case 'localdate as text using T separator': case 'UTC as text': case 'UTC as text using T separator': case 'UTC as text using Z timezone': case 'UTC as text using T separator and Z timezone': return value.getFullYear() + '-' + doubleDigit(value.getMonth()) + '-' + doubleDigit(value.getDate()) case 'Julian day as real number': return millisecondsToJulian(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate())) case 'Unix time seconds as integer': return Math.trunc(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / 1000) case 'Unix time milliseconds as integer': return Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } throw new Error(`Invalid localDate value to send to the db: ${value} (type ${typeof value})`) case 'localTime': if (value instanceof Date && !isNaN(value.getTime())) { const dateTimeFormat = this.getDateTimeFormat('time') switch (dateTimeFormat) { case 'localdate as text': case 'localdate as text using T separator': return doubleDigit(value.getHours()) + ':' + doubleDigit(value.getMinutes()) + ':' + doubleDigit(value.getSeconds()) + tripleDigitFraction(value.getMilliseconds()) case 'UTC as text': case 'UTC as text using T separator': return doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) case 'UTC as text using Z timezone': case 'UTC as text using T separator and Z timezone': return doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) + 'Z' case 'Julian day as real number': return millisecondsToJulian(Date.UTC(1970, 0, 1, value.getUTCHours(), value.getUTCMinutes(), value.getUTCSeconds(), value.getUTCMilliseconds())) - 2440587.5 /* 1970-01-01 */ case 'Unix time seconds as integer': return Math.trunc(Date.UTC(1970, 0, 1, value.getUTCHours(), value.getUTCMinutes(), value.getUTCSeconds(), value.getUTCMilliseconds()) / 1000) case 'Unix time milliseconds as integer': return Date.UTC(1970, 0, 1, value.getUTCHours(), value.getUTCMinutes(), value.getUTCSeconds(), value.getUTCMilliseconds()) default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } throw new Error(`Invalid localTime value to send to the db: ${value} (type ${typeof value})`) case 'localDateTime': if (value instanceof Date && !isNaN(value.getTime())) { const dateTimeFormat = this.getDateTimeFormat('dateTime') switch (dateTimeFormat) { case 'localdate as text': return value.getFullYear() + '-' + doubleDigit(value.getMonth()) + '-' + doubleDigit(value.getDate()) + ' ' + doubleDigit(value.getHours()) + ':' + doubleDigit(value.getMinutes()) + ':' + doubleDigit(value.getSeconds()) + tripleDigitFraction(value.getMilliseconds()) case 'localdate as text using T separator': return value.getFullYear() + '-' + doubleDigit(value.getMonth()) + '-' + doubleDigit(value.getDate()) + 'T' + doubleDigit(value.getHours()) + ':' + doubleDigit(value.getMinutes()) + ':' + doubleDigit(value.getSeconds()) + tripleDigitFraction(value.getMilliseconds()) case 'UTC as text': return value.getUTCFullYear() + '-' + doubleDigit(value.getUTCMonth()) + '-' + doubleDigit(value.getUTCDate()) + ' ' + doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) case 'UTC as text using T separator': return value.getUTCFullYear() + '-' + doubleDigit(value.getUTCMonth()) + '-' + doubleDigit(value.getUTCDate()) + 'T' + doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) case 'UTC as text using Z timezone': return value.getUTCFullYear() + '-' + doubleDigit(value.getUTCMonth()) + '-' + doubleDigit(value.getUTCDate()) + ' ' + doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) + 'Z' case 'UTC as text using T separator and Z timezone': return value.getUTCFullYear() + '-' + doubleDigit(value.getUTCMonth()) + '-' + doubleDigit(value.getUTCDate()) + 'T' + doubleDigit(value.getUTCHours()) + ':' + doubleDigit(value.getUTCMinutes()) + ':' + doubleDigit(value.getUTCSeconds()) + tripleDigitFraction(value.getUTCMilliseconds()) + 'Z' case 'Julian day as real number': return millisecondsToJulian(value.getTime()) case 'Unix time seconds as integer': return Math.trunc(value.getTime() / 1000) case 'Unix time milliseconds as integer': return value.getTime() default: throw new Error('Invalid sqlite date time format: ' + dateTimeFormat) } } throw new Error(`Invalid localDateTime value to send to the db: ${value} (type ${typeof value})`) } return super.transformValueToDB(value, type) } } function doubleDigit(value: number): string { if (value > 9) { return '' + value } else { return '0' + value } } function tripleDigit(value: number): string { if (value > 99) { return '' + value } else if (value > 9) { return '0' + value } else { return '00' + value } } function tripleDigitFraction(value: number): string { if (value > 0) { return '.' + tripleDigit(value) } return '' } function millisecondsToJulian(value: number): number { return value / 86400000.0 + 2440587.5 } function julianToMilliseconds(value: number): number { return (value - 2440587.5) * 86400000.0 } function containsTimezone(value: string): boolean { return /(([\+\-]\d\d?(:\d\d?)?)|Z)$/.test(value) } function containsDate(value: string): boolean { return /^\d+-\d\d?-\d\d?(\s|T)/.test(value) }
the_stack
import {ComponentFixture, fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {ActivatedRoute, Router} from '@angular/router'; import {RouterTestingModule} from '@angular/router/testing'; import {of} from 'rxjs'; import {Status} from '../../models/device'; import {DeviceService} from '../../services/device'; import {Dialog} from '../../services/dialog'; import {ShelfService} from '../../services/shelf'; import {ActivatedRouteMock, DeviceServiceMock, SHELF_CAPACITY_1, ShelfServiceMock} from '../../testing/mocks'; import {AuditTable, AuditTableModule} from './index'; describe('AuditTableComponent', () => { let fixture: ComponentFixture<AuditTable>; let auditTable: AuditTable; let router: Router; beforeEach(fakeAsync(() => { TestBed .configureTestingModule({ imports: [ RouterTestingModule, AuditTableModule, BrowserAnimationsModule, ], providers: [ {provide: ActivatedRoute, useClass: ActivatedRouteMock}, {provide: ShelfService, useClass: ShelfServiceMock}, {provide: DeviceService, useClass: DeviceServiceMock}, ], }) .compileComponents(); flushMicrotasks(); fixture = TestBed.createComponent(AuditTable); auditTable = fixture.debugElement.componentInstance; router = TestBed.get(Router); })); it('creates the AuditTable', () => { expect(auditTable).toBeTruthy(); expect(auditTable.devicesToBeCheckedIn.length).toBe(0); }); it('renders card title in a mat-card-title', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.mat-card-title').textContent) .toContain('Friendly name 1'); }); it('renders "Identifier" inside row-header', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.header-row').textContent) .toContain('Identifier'); }); it('renders an mat-input with placeholder inside card title', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const inputContainer = compiled.querySelector('.mat-card-title mat-form-field'); expect(inputContainer).toBeTruthy(); expect(inputContainer.querySelector('input[matInput]') .getAttribute('placeholder')) .toBe('Identifier'); }); it('has a audit empty button at beginning', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditEmptyButton = compiled.querySelector('button.audit'); expect(auditEmptyButton).toBeTruthy(); expect(auditEmptyButton.textContent).toContain('Audit Empty'); }); it('enables audit button with only READY elements in the list', () => { auditTable.devicesToBeCheckedIn = [ { deviceId: '321653', status: Status.READY, }, ]; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); expect(auditButton).toBeTruthy(); expect(auditButton.getAttribute('disabled')).toBeNull(); }); it('disables audit button with ERROR elements only in the list', () => { auditTable.devicesToBeCheckedIn = [ { deviceId: '321653', status: Status.READY, }, { deviceId: '321653', status: Status.ERROR, }, ]; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); expect(auditButton).toBeTruthy(); expect(auditButton.hasAttribute('disabled')).toBeTruthy(); }); it('calls shelf service with deviceId when audit button is clicked', fakeAsync(() => { auditTable.devicesToBeCheckedIn = [ { deviceId: '321653', status: Status.READY, }, ]; expect(auditTable.isEmpty).not.toBeTruthy(); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); const shelfService = TestBed.get(ShelfService); spyOn(shelfService, 'audit').and.callThrough(); spyOn(router, 'navigate'); auditButton.click(); flushMicrotasks(); expect(shelfService.audit).toHaveBeenCalledWith(auditTable.shelf, [ '321653' ]); })); it('successfully calls shelf service with 3 devices when shelf capacity is 1', fakeAsync(() => { auditTable.devicesToBeCheckedIn = [ { deviceId: '321653', status: Status.READY, }, { deviceId: '123456', status: Status.READY, }, { deviceId: '7891011', status: Status.READY, }, ]; expect(auditTable.isEmpty).not.toBeTruthy(); auditTable.shelf = SHELF_CAPACITY_1; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); const shelfService = TestBed.get(ShelfService); spyOn(shelfService, 'audit').and.callThrough(); spyOn(router, 'navigate'); auditButton.click(); flushMicrotasks(); expect(shelfService.audit).toHaveBeenCalledWith(auditTable.shelf, [ '321653', '123456', '7891011' ]); })); it('calls shelf service without deviceId when audit button is clicked and dialog is confirmed', fakeAsync(() => { auditTable.devicesToBeCheckedIn = []; expect(auditTable.isEmpty).toBeTruthy(); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); const shelfService = TestBed.get(ShelfService); spyOn(shelfService, 'audit').and.callThrough(); const dialog = TestBed.get(Dialog); spyOn(dialog, 'confirm').and.returnValue(of(true)); spyOn(router, 'navigate'); auditButton.click(); flushMicrotasks(); expect(shelfService.audit).toHaveBeenCalledWith(auditTable.shelf); })); it('does NOT call shelf service when audit button is clicked and dialog is NOT confirmed', fakeAsync(() => { auditTable.devicesToBeCheckedIn = []; expect(auditTable.isEmpty).toBeTruthy(); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const auditButton = compiled.querySelector('button.audit'); const shelfService = TestBed.get(ShelfService); spyOn(shelfService, 'audit').and.callThrough(); const dialog = TestBed.get(Dialog); spyOn(dialog, 'confirm').and.returnValue(of(false)); auditButton.click(); flushMicrotasks(); expect(shelfService.audit).not.toHaveBeenCalled(); })); it('increment devicesToBeChecked when Add button is clicked', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardTitle = matCard.querySelector('.mat-card-title'); const matCardContent = matCard.querySelector('.mat-card-content'); const inputElement = matCardTitle.querySelector('mat-form-field input'); const addButton = matCardTitle.querySelector('.add-to-audit-list-button'); inputElement.value = '123123'; addButton.dispatchEvent(new Event('click')); expect(auditTable.devicesToBeCheckedIn.length).toBe(1); expect(auditTable.devicesToBeCheckedIn[0].deviceId).toBe('123123'); fixture.detectChanges(); expect(matCardContent.querySelectorAll('.mat-list > .mat-list-item').length) .toBe(1); }); it('increment devicesToBeChecked when "Enter" button is released', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardTitle = matCard.querySelector('.mat-card-title'); const matCardContent = matCard.querySelector('.mat-card-content'); const inputElement = matCardTitle.querySelector('mat-form-field input'); inputElement.value = '123123'; inputElement.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', })); expect(auditTable.devicesToBeCheckedIn.length).toBe(1); expect(auditTable.devicesToBeCheckedIn[0].deviceId).toBe('123123'); fixture.detectChanges(); expect(matCardContent.querySelectorAll('.mat-list > .mat-list-item').length) .toBe(1); }); it('increments devicesToBeChecked when Add button is clicked for a device with a space', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardTitle = matCard.querySelector('.mat-card-title'); const matCardContent = matCard.querySelector('.mat-card-content'); const inputElement = matCardTitle.querySelector('mat-form-field input'); const addButton = matCardTitle.querySelector('.add-to-audit-list-button'); inputElement.value = ' 123123 '; addButton.dispatchEvent(new Event('click')); expect(auditTable.devicesToBeCheckedIn.length).toBe(1); expect(auditTable.devicesToBeCheckedIn[0].deviceId).toBe('123123'); fixture.detectChanges(); expect( matCardContent.querySelectorAll('.mat-list > .mat-list-item').length) .toBe(1); }); it('decrement devicesToBeChecked when "Close" button is clicked.', () => { auditTable.devicesToBeCheckedIn = [ { deviceId: '321653', status: Status.READY, }, { deviceId: '156854168', status: Status.READY, }, ]; fixture.detectChanges(); expect(auditTable.devicesToBeCheckedIn.length).toBe(2); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardContent = matCard.querySelector('.mat-card-content'); const matListItems = matCardContent.querySelectorAll('mat-list > mat-list-item'); expect(matListItems.length).toBe(2); const closeButton = matListItems[0].querySelector('button:last-of-type'); closeButton.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(matCardContent.querySelectorAll('.mat-list > .mat-list-item').length) .toBe(1); }); it('check icon is present when devices are is in a READY status', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardContent = matCard.querySelector('.mat-card-content'); auditTable.devicesToBeCheckedIn = [{ deviceId: '12123', status: Status.READY, }]; fixture.detectChanges(); const devicesOnScreen = matCardContent.querySelectorAll('.mat-list > .mat-list-item'); expect(devicesOnScreen.length).toBe(1); expect(devicesOnScreen[0].querySelector('mat-icon')).not.toBe(null); expect(devicesOnScreen[0].querySelector('mat-icon').textContent) .toContain('check'); }); it('error icon is present when devices are is in a ERROR status', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; const matCard = compiled.querySelector('.mat-card'); const matCardContent = matCard.querySelector('.mat-card-content'); auditTable.devicesToBeCheckedIn = [{ deviceId: '12123', status: Status.ERROR, }]; fixture.detectChanges(); const devicesOnScreen = matCardContent.querySelectorAll('.mat-list > .mat-list-item'); expect(devicesOnScreen.length).toBe(1); expect(devicesOnScreen[0].querySelector('mat-icon')).not.toBe(null); expect(devicesOnScreen[0].querySelector('mat-icon').textContent) .toContain('error'); }); });
the_stack
import { revcom } from '@jbrowse/core/util' export interface Mismatch { qual?: number start: number length: number type: string base: string altbase?: string seq?: string cliplen?: number } export function parseCigar(cigar: string) { return (cigar || '').split(/([MIDNSHPX=])/) } export function cigarToMismatches( ops: string[], seq: string, qual?: Buffer, ): Mismatch[] { let currOffset = 0 let seqOffset = 0 const mismatches: Mismatch[] = [] for (let i = 0; i < ops.length - 1; i += 2) { const len = +ops[i] const op = ops[i + 1] if (op === 'M' || op === '=' || op === 'E') { seqOffset += len } if (op === 'I') { mismatches.push({ start: currOffset, type: 'insertion', base: `${len}`, length: 0, }) seqOffset += len } else if (op === 'D') { mismatches.push({ start: currOffset, type: 'deletion', base: '*', length: len, }) } else if (op === 'N') { mismatches.push({ start: currOffset, type: 'skip', base: 'N', length: len, }) } else if (op === 'X') { const r = seq.slice(seqOffset, seqOffset + len) const q = qual?.slice(seqOffset, seqOffset + len) || [] for (let j = 0; j < len; j++) { mismatches.push({ start: currOffset + j, type: 'mismatch', base: r[j], qual: q[j], length: 1, }) } seqOffset += len } else if (op === 'H') { mismatches.push({ start: currOffset, type: 'hardclip', base: `H${len}`, cliplen: len, length: 1, }) } else if (op === 'S') { mismatches.push({ start: currOffset, type: 'softclip', base: `S${len}`, cliplen: len, length: 1, }) seqOffset += len } if (op !== 'I' && op !== 'S' && op !== 'H') { currOffset += len } } return mismatches } /** * parse a SAM MD tag to find mismatching bases of the template versus the reference * @returns array of mismatches and their positions */ export function mdToMismatches( mdstring: string, cigarOps: string[], cigarMismatches: Mismatch[], seq: string, qual?: Buffer, ): Mismatch[] { const mismatchRecords: Mismatch[] = [] let curr: Mismatch = { start: 0, base: '', length: 0, type: 'mismatch' } const skips = cigarMismatches.filter(cigar => cigar.type === 'skip') let lastCigar = 0 let lastTemplateOffset = 0 let lastRefOffset = 0 let lastSkipPos = 0 // convert a position on the reference sequence to a position // on the template sequence, taking into account hard and soft // clipping of reads function nextRecord(): void { mismatchRecords.push(curr) // get a new mismatch record ready curr = { start: curr.start + curr.length, length: 0, base: '', type: 'mismatch', } } function getTemplateCoordLocal(refCoord: number): number { let templateOffset = lastTemplateOffset let refOffset = lastRefOffset for ( let i = lastCigar; i < cigarOps.length && refOffset <= refCoord; i += 2, lastCigar = i ) { const len = +cigarOps[i] const op = cigarOps[i + 1] if (op === 'S' || op === 'I') { templateOffset += len } else if (op === 'D' || op === 'P' || op === 'N') { refOffset += len } else if (op !== 'H') { templateOffset += len refOffset += len } } lastTemplateOffset = templateOffset lastRefOffset = refOffset return templateOffset - (refOffset - refCoord) } // now actually parse the MD string const md = mdstring.match(/(\d+|\^[a-z]+|[a-z])/gi) || [] for (let i = 0; i < md.length; i++) { const token = md[i] if (token.match(/^\d/)) { curr.start += parseInt(token, 10) } else if (token.match(/^\^/)) { curr.length = token.length - 1 curr.base = '*' curr.type = 'deletion' curr.seq = token.substring(1) nextRecord() } else if (token.match(/^[a-z]/i)) { // mismatch for (let j = 0; j < token.length; j += 1) { curr.length = 1 while (lastSkipPos < skips.length) { const mismatch = skips[lastSkipPos] if (curr.start >= mismatch.start) { curr.start += mismatch.length lastSkipPos++ } else { break } } const s = cigarOps ? getTemplateCoordLocal(curr.start) : curr.start curr.base = seq ? seq.substr(s, 1) : 'X' const qualScore = qual?.slice(s, s + 1)[0] if (qualScore) { curr.qual = qualScore } curr.altbase = token nextRecord() } } } return mismatchRecords } export function getTemplateCoord(refCoord: number, cigarOps: string[]): number { let templateOffset = 0 let refOffset = 0 for (let i = 0; i < cigarOps.length && refOffset <= refCoord; i += 2) { const len = +cigarOps[i] const op = cigarOps[i + 1] if (op === 'S' || op === 'I') { templateOffset += len } else if (op === 'D' || op === 'P') { refOffset += len } else if (op !== 'H') { templateOffset += len refOffset += len } } return templateOffset - (refOffset - refCoord) } export function getMismatches( cigarString: string, mdString: string, seq: string, qual?: Buffer, ): Mismatch[] { let mismatches: Mismatch[] = [] let cigarOps: string[] = [] // parse the CIGAR tag if it has one if (cigarString) { cigarOps = parseCigar(cigarString) mismatches = mismatches.concat(cigarToMismatches(cigarOps, seq, qual)) } // now let's look for CRAM or MD mismatches if (mdString) { mismatches = mismatches.concat( mdToMismatches(mdString, cigarOps, mismatches, seq, qual), ) } // uniqify the mismatches const seen: { [index: string]: boolean } = {} return mismatches.filter(m => { const key = `${m.type},${m.start},${m.length}` const s = seen[key] seen[key] = true return !s }) } // adapted from minimap2 code static void write_MD_core function export function generateMD(target: string, query: string, cigar: string) { let queryOffset = 0 let targetOffset = 0 let lengthMD = 0 if (!target) { console.warn('no ref supplied to generateMD') return '' } const cigarOps = parseCigar(cigar) let str = '' for (let i = 0; i < cigarOps.length; i += 2) { const len = +cigarOps[i] const op = cigarOps[i + 1] if (op === 'M' || op === 'X' || op === '=') { for (let j = 0; j < len; j++) { if ( query[queryOffset + j].toLowerCase() !== target[targetOffset + j].toLowerCase() ) { str += `${lengthMD}${target[targetOffset + j].toUpperCase()}` lengthMD = 0 } else { lengthMD++ } } queryOffset += len targetOffset += len } else if (op === 'I') { queryOffset += len } else if (op === 'D') { let tmp = '' for (let j = 0; j < len; j++) { tmp += target[targetOffset + j].toUpperCase() } str += `${lengthMD}^${tmp}` lengthMD = 0 targetOffset += len } else if (op === 'N') { targetOffset += len } else if (op === 'S') { queryOffset += len } } if (lengthMD > 0) { str += lengthMD } return str } // get relative reference sequence positions for positions given relative to // the read sequence export function* getNextRefPos(cigarOps: string[], positions: number[]) { let cigarIdx = 0 let readPos = 0 let refPos = 0 for (let i = 0; i < positions.length; i++) { const pos = positions[i] for (; cigarIdx < cigarOps.length && readPos < pos; cigarIdx += 2) { const len = +cigarOps[cigarIdx] const op = cigarOps[cigarIdx + 1] if (op === 'S' || op === 'I') { readPos += len } else if (op === 'D' || op === 'N') { refPos += len } else if (op === 'M' || op === 'X' || op === '=') { readPos += len refPos += len } } yield positions[i] - readPos + refPos } } export function getModificationPositions( mm: string, fseq: string, fstrand: number, ) { const seq = fstrand === -1 ? revcom(fseq) : fseq return mm .split(';') .filter(mod => !!mod) .map(mod => { const [basemod, ...skips] = mod.split(',') // regexes based on parse_mm.pl from hts-specs const matches = basemod.match(/([A-Z])([-+])([^,]+)/) if (!matches) { throw new Error('bad format for MM tag') } const [, base, strand, typestr] = matches // can be a multi e.g. C+mh for both meth (m) and hydroxymeth (h) so // split, and they can also be chemical codes (ChEBI) e.g. C+16061 const types = typestr.split(/(\d+|.)/).filter(f => !!f) if (strand === '-') { console.warn('unsupported negative strand modifications') // make sure to return a somewhat matching type even in this case return { type: 'unsupported', positions: [] } } // this logic also based on parse_mm.pl from hts-specs is that in the // sequence of the read, if we have a modification type e.g. C+m;2 and a // sequence ACGTACGTAC we skip the two instances of C and go to the last // C return types.map(type => { let i = 0 return { type, positions: skips .map(score => +score) .map(delta => { do { if (base === 'N' || base === seq[i]) { delta-- } i++ } while (delta >= 0 && i < seq.length) const temp = i - 1 return fstrand === -1 ? seq.length - 1 - temp : temp }) .sort((a, b) => a - b), } }) }) .flat() } export function getModificationTypes(mm: string) { const mods = mm.split(';') return mods .filter(mod => !!mod) .map(mod => { const [basemod] = mod.split(',') const matches = basemod.match(/([A-Z])([-+])([^,]+)/) if (!matches) { throw new Error('bad format for MM tag') } const [, , , typestr] = matches // can be a multi e.g. C+mh for both meth (m) and hydroxymeth (h) so // split, and they can also be chemical codes (ChEBI) e.g. C+16061 return typestr.split(/(\d+|.)/).filter(f => !!f) }) .flat() }
the_stack
import * as dartStyle from 'dart-style'; import * as path from 'path'; import * as ts from 'typescript'; import {OutputContext, Transpiler} from './main'; /** * Map from identifier name to resolved type. * Example: 'E' should map to a TypeNode for number when resolving a usage of MyArray<number> * where MyArray is the alias type: * type MyArray<E> = Array<T> */ export type ResolvedTypeMap = Map<string, ts.TypeNode>; /*** * Options for how TypeScript types are represented as Dart types. */ export interface TypeDisplayOptions { /// We are displaying the type inside a comment so we don't have to restrict to valid Dart syntax. /// For example, we can display string literal type using the regular TypeScript syntax. /// /// Example: /// TypeScript type: number|string /// Dart inside comment: num|String /// Dart outside comment: dynamic /* num|string */ insideComment?: boolean; /// Dart has additional restrictions for what types are valid to emit inside a type argument. For /// example, "void" is not valid inside a type argument so Null has to be used instead. /// /// Example: /// TypeScript type: Foo<void> /// Dart inside type argument: Foo<Null> /// Dart outside type argument: N/A /// TypeScript type: bar():void /// Dart inside type argument: N/A /// Dart outside type argument: void bar(); insideTypeArgument?: boolean; /// Indicates that we should not append an additional comment indicating what the true TypeScript /// type was for cases where Dart cannot express the type precisely. /// /// Example: /// TypeScript type: number|string /// Dart hide comment: dynamic /// Dart show comment: dynamic /*number|string*/ hideComment?: boolean; /** * Type arguments associated with the current type to display. * Arguments are emitted directly in normal cases but in the case of type aliases we have to * propagate and substitute type arguments. */ typeArguments?: ts.NodeArray<ts.TypeNode>; /** * Parameter declarations to substitute. This is required to support type aliases with type * arguments that are not representable in Dart. */ resolvedTypeArguments?: ResolvedTypeMap; } /** * Summary information on what is imported via a particular import. */ export class ImportSummary { showAll = false; shown: Set<String> = new Set(); asPrefix: string; } export type Constructor = ts.ConstructorDeclaration|ts.ConstructSignatureDeclaration; export type ClassLike = ts.ClassLikeDeclaration|ts.InterfaceDeclaration; /** * Interface extending the true InterfaceDeclaration interface to add optional state we store on * interfaces to simplify conversion to Dart classes. */ export interface ExtendedInterfaceDeclaration extends ts.InterfaceDeclaration { /** * The type associated with this interface that we want to treat as the concrete location of this * interface to enable interfaces that act like constructors. Because Dart does not permit calling * objects like constructors we have to add this workaround. */ constructedType?: ts.InterfaceDeclaration|ts.TypeLiteralNode; } export function ident(n: ts.Node): string { if (ts.isIdentifier(n) || ts.isStringLiteralLike(n)) { return n.text; } if (ts.isQualifiedName(n)) { const leftName = ident(n.left); if (leftName) { return leftName + '.' + ident(n.right); } } return null; } export function isFunctionTypedefLikeInterface(ifDecl: ts.InterfaceDeclaration): boolean { return ifDecl.members && ifDecl.members.length === 1 && ts.isCallSignatureDeclaration(ifDecl.members[0]); } export function isExtendsClause(heritageClause: ts.HeritageClause) { return heritageClause.token === ts.SyntaxKind.ExtendsKeyword && !ts.isInterfaceDeclaration(heritageClause.parent); } export function isConstructor(n: ts.Node): n is Constructor { return ts.isConstructorDeclaration(n) || ts.isConstructSignatureDeclaration(n); } export function isStatic(n: ts.Node): boolean { let hasStatic = false; ts.forEachChild(n, (child) => { if (child.kind === ts.SyntaxKind.StaticKeyword) { hasStatic = true; } }); return hasStatic; } export function isReadonly(n: ts.Node): boolean { let hasReadonly = false; ts.forEachChild(n, (child) => { if (child.kind === ts.SyntaxKind.ReadonlyKeyword) { hasReadonly = true; } }); return hasReadonly; } export function isCallableType(type: ts.TypeNode, tc: ts.TypeChecker): boolean { if (isFunctionType(type, tc)) return true; if (ts.isTypeReferenceNode(type)) { if (tc.getSignaturesOfType(tc.getTypeAtLocation(type), ts.SignatureKind.Call).length > 0) return true; } return false; } /** * Returns whether a type declaration is on we can generate a named Dart type for. * For unsupported alias types we need to manually substitute the expression * the alias corresponds to in call sites. */ export function supportedTypeDeclaration(decl: ts.Declaration): boolean { if (ts.isTypeAliasDeclaration(decl)) { let type = decl.type; return ts.isTypeLiteralNode(type) || ts.isFunctionTypeNode(type); } return true; } export function isFunctionType(type: ts.TypeNode, tc: ts.TypeChecker): boolean { if (ts.isFunctionTypeNode(type)) return true; if (ts.isTypeReferenceNode(type)) { let t = tc.getTypeAtLocation(type); if (t.symbol && t.symbol.flags & ts.SymbolFlags.Function) return true; } if (ts.isIntersectionTypeNode(type)) { let types = type.types; for (let i = 0; i < types.length; ++i) { if (isFunctionType(types[i], tc)) { return true; } } return false; } if (ts.isUnionTypeNode(type)) { let types = type.types; for (let i = 0; i < types.length; ++i) { if (!isFunctionType(types[i], tc)) { return false; } } return true; } // Warning: if the kind is a reference type and the reference is to an // interface that only has a call member we will not return that it is a // function type. if (ts.isTypeLiteralNode(type)) { let members = type.members; for (let i = 0; i < members.length; ++i) { if (ts.isCallSignatureDeclaration(members[i])) { return false; } } return true; } return false; } /** * Whether a parameter declaration is specifying information about the type of "this" passed to * the function instead of being a normal type parameter representable by a Dart type. */ export function isThisParameter(param: ts.ParameterDeclaration): boolean { return param.name && ts.isIdentifier(param.name) && param.name.text === 'this'; } /** * Dart does not have a concept of binding the type of the "this" parameter to a method. */ export function filterThisParameter(params: ts.NodeArray<ts.ParameterDeclaration>): ts.ParameterDeclaration[] { let ret: ts.ParameterDeclaration[] = []; for (let i = 0; i < params.length; i++) { let param = params[i]; if (!isThisParameter(param)) { ret.push(param); } } return ret; } export function isTypeNode(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.IntersectionType: case ts.SyntaxKind.UnionType: case ts.SyntaxKind.ParenthesizedType: case ts.SyntaxKind.TypeReference: case ts.SyntaxKind.TypeLiteral: case ts.SyntaxKind.LastTypeNode: case ts.SyntaxKind.LiteralType: case ts.SyntaxKind.ArrayType: case ts.SyntaxKind.TypeOperator: case ts.SyntaxKind.IndexedAccessType: case ts.SyntaxKind.MappedType: case ts.SyntaxKind.TypePredicate: case ts.SyntaxKind.TypeQuery: case ts.SyntaxKind.TupleType: case ts.SyntaxKind.NumberKeyword: case ts.SyntaxKind.StringKeyword: case ts.SyntaxKind.VoidKeyword: case ts.SyntaxKind.NullKeyword: case ts.SyntaxKind.UndefinedKeyword: case ts.SyntaxKind.BooleanKeyword: case ts.SyntaxKind.AnyKeyword: case ts.SyntaxKind.NeverKeyword: case ts.SyntaxKind.FunctionType: case ts.SyntaxKind.ThisType: return true; default: return false; } } export function isPromise(type: ts.TypeNode): boolean { return type && ts.isTypeReferenceNode(type) && ident(type.typeName) === 'Promise'; } export function isCallable(decl: ClassLike): boolean { let members = decl.members as ReadonlyArray<ts.ClassElement>; return members.some((member) => { return member.kind === ts.SyntaxKind.CallSignature; }); } export function copyLocation(src: ts.Node, dest: ts.Node) { dest.pos = src.pos; dest.end = src.end; dest.parent = src.parent; } export function cloneNodeArray<T extends ts.Node>(src?: ts.NodeArray<T>): ts.NodeArray<T>| undefined { if (!src) { return undefined; } const clone = ts.createNodeArray(src.map(ts.getMutableClone)); copyNodeArrayLocation(src, clone); return clone; } export function copyNodeArrayLocation(src: ts.TextRange, dest: ts.NodeArray<any>) { dest.pos = src.pos; dest.end = src.end; } export function getAncestor(n: ts.Node, kind: ts.SyntaxKind): ts.Node { for (let parent = n; parent; parent = parent.parent) { if (parent.kind === kind) return parent; } return null; } export function getEnclosingClass(n: ts.Node): ClassLike { while (n) { if (ts.isClassDeclaration(n) || ts.isInterfaceDeclaration(n)) { return <ClassLike>n; } n = n.parent; } return null; } export function isConstCall(node: ts.CallExpression): boolean { return node && ident(node.expression) === 'CONST_EXPR'; } export function isInsideConstExpr(node: ts.Node): boolean { return isConstCall(<ts.CallExpression>getAncestor(node, ts.SyntaxKind.CallExpression)); } export function getModuleBlock(moduleDecl: ts.ModuleDeclaration): ts.ModuleBlock { while (ts.isModuleDeclaration(moduleDecl.body)) { moduleDecl = moduleDecl.body; } if (ts.isModuleBlock(moduleDecl.body)) { return moduleDecl.body; } else { throw new Error('Module body must be a module block.'); } } /** * Determine the full module name including dots. * * e.g. returns 'foo.bar' for a declaration of namespace or module foo.bar */ export function getModuleName(moduleDecl: ts.ModuleDeclaration): string { let name = moduleDecl.name.text; while (ts.isModuleDeclaration(moduleDecl.body)) { moduleDecl = moduleDecl.body; name += '.' + moduleDecl.name.text; } return name; } export function formatType(s: string, comment: string, options: TypeDisplayOptions): string { if (!comment || options.hideComment) { return s; } else if (options.insideComment) { // When inside a comment we only need to emit the comment version which // is the syntax we would like to use if Dart supported all language // features we would like to use for interop. return comment; } else { let sb = s + '/*'; // Check if the comment is a valid type name in which case it is safe to use the Dart code // written in comments syntax. const stubToMakeTypeValidStatement = ' DUMMY_VARIABLE_NAME;'; comment = comment.trim(); let statement = comment + stubToMakeTypeValidStatement; let result = dartStyle.formatCode(statement); if (!result.error) { result.code = result.code.trim(); let expectedStubIndex = result.code.length - stubToMakeTypeValidStatement.length; if (result.code.lastIndexOf(stubToMakeTypeValidStatement) === expectedStubIndex) { comment = result.code.substring(0, expectedStubIndex).trim(); } } sb += comment; sb += '*/'; return sb; } } export class TranspilerBase { private idCounter = 0; constructor(protected transpiler: Transpiler) {} visit(n: ts.Node) { this.transpiler.visit(n); } pushContext(context: OutputContext) { this.transpiler.pushContext(context); } popContext() { this.transpiler.popContext(); } emit(s: string) { this.transpiler.emit(s); } emitNoSpace(s: string) { this.transpiler.emitNoSpace(s); } emitType(s: string, comment: string) { this.transpiler.emitType(s, comment); } maybeLineBreak() { return this.transpiler.maybeLineBreak(); } enterCodeComment() { return this.transpiler.enterCodeComment(); } exitCodeComment() { return this.transpiler.exitCodeComment(); } maybeWrapInCodeComment({shouldWrap = true, newLine = false}, emit: () => void): void { if (shouldWrap) { this.enterCodeComment(); } emit(); if (shouldWrap) { this.exitCodeComment(); } if (newLine) { this.emit('\n'); } } enterTypeArguments() { this.transpiler.enterTypeArgument(); } exitTypeArguments() { this.transpiler.exitTypeArgument(); } get insideTypeArgument() { return this.transpiler.insideTypeArgument; } get insideCodeComment() { return this.transpiler.insideCodeComment; } getImportSummary(libraryUri: string): ImportSummary { if (!this.transpiler.imports.has(libraryUri)) { let summary = new ImportSummary(); this.transpiler.imports.set(libraryUri, summary); return summary; } return this.transpiler.imports.get(libraryUri); } /** * Add an import. If an identifier is specified, only show that name. */ addImport(libraryUri: string, identifier?: string): ImportSummary { let summary = this.getImportSummary(libraryUri); if (identifier) { summary.shown.add(identifier); } else { summary.showAll = true; } return summary; } /** * Return resolved name possibly including a prefix for the identifier. */ resolveImportForSourceFile(sourceFile: ts.SourceFile, context: ts.SourceFile, identifier: string): string { if (sourceFile === context) { return identifier; } if (sourceFile.hasNoDefaultLib) { // We don't want to emit imports to default lib libraries as we replace with Dart equivalents // such as dart:html, etc. return identifier; } const relativePath = path.relative(path.dirname(context.fileName), sourceFile.fileName); const fileName = this.getDartFileName(relativePath); const identifierParts = identifier.split('.'); identifier = identifierParts[identifierParts.length - 1]; const summary = this.addImport(this.transpiler.getDartFileName(fileName), identifier); if (summary.asPrefix) { return summary.asPrefix + '.' + identifier; } return identifier; } reportError(n: ts.Node, message: string) { this.transpiler.reportError(n, message); } visitNode(n: ts.Node): boolean { throw new Error('not implemented'); } visitEach(nodes: ts.NodeArray<ts.Node>) { nodes.forEach((n) => this.visit(n)); } visitEachIfPresent(nodes?: ts.NodeArray<ts.Node>) { if (nodes) this.visitEach(nodes); } visitList(nodes: ts.NodeArray<ts.Node>, separator?: string) { separator = separator || ','; for (let i = 0; i < nodes.length; i++) { this.visit(nodes[i]); if (i < nodes.length - 1) this.emitNoSpace(separator); } } /** * Returns whether any parameters were actually emitted. */ visitParameterList(nodes: ts.ParameterDeclaration[], namesOnly: boolean): boolean { let emittedParameters = false; for (let i = 0; i < nodes.length; ++i) { let param = nodes[i]; if (!this.insideCodeComment && isThisParameter(param)) { // Emit the this type in a comment as it could be of interest to Dart users who are // calling allowInteropCaptureThis to bind a Dart method. this.enterCodeComment(); this.visit(param.type); this.emit('this'); this.exitCodeComment(); continue; } if (emittedParameters) { this.emitNoSpace(','); } if (namesOnly) { this.emit(ident(param.name)); } else { this.visit(param); } emittedParameters = true; } return emittedParameters; } uniqueId(name: string): string { const id = this.idCounter++; return `_${name}\$\$js_facade_gen\$${id}`; } assert(c: ts.Node, condition: boolean, reason: string): void { if (!condition) { this.reportError(c, reason); throw new Error(reason); } } getAncestor(n: ts.Node, kind: ts.SyntaxKind): ts.Node { for (let parent = n; parent; parent = parent.parent) { if (parent.kind === kind) return parent; } return null; } hasAncestor(n: ts.Node, kind: ts.SyntaxKind): boolean { return !!getAncestor(n, kind); } hasAnnotation(decorators: ts.NodeArray<ts.Decorator>, name: string): boolean { if (!decorators) return false; return decorators.some((d) => { let decName = ident(d.expression); if (decName === name) return true; if (!ts.isCallExpression(d.expression)) return false; let callExpr = d.expression; decName = ident(callExpr.expression); return decName === name; }); } hasNodeFlag(n: ts.Declaration, flag: ts.NodeFlags): boolean { return n && (ts.getCombinedNodeFlags(n) & flag) !== 0 || false; } hasModifierFlag(n: ts.Declaration, flag: ts.ModifierFlags): boolean { return n && (ts.getCombinedModifierFlags(n) & flag) !== 0 || false; } getRelativeFileName(fileName: string): string { return this.transpiler.getRelativeFileName(fileName); } getDartFileName(fileName?: string): string { return this.transpiler.getDartFileName(fileName); } maybeVisitTypeArguments(n: {typeArguments?: ts.NodeArray<ts.TypeNode>}) { if (n.typeArguments) { this.emitNoSpace('<'); this.enterTypeArguments(); this.visitList(n.typeArguments); this.exitTypeArguments(); this.emitNoSpace('>'); } } visitParameters(parameters: ts.NodeArray<ts.ParameterDeclaration>, {namesOnly = false}) { this.emitNoSpace('('); let firstInitParamIdx = 0; for (; firstInitParamIdx < parameters.length; firstInitParamIdx++) { // ObjectBindingPatterns are handled within the parameter visit. let isOpt = parameters[firstInitParamIdx].initializer || parameters[firstInitParamIdx].questionToken || parameters[firstInitParamIdx].dotDotDotToken; if (isOpt && !ts.isObjectBindingPattern(parameters[firstInitParamIdx].name)) { break; } } let hasValidParameters = false; if (firstInitParamIdx !== 0) { let requiredParams = parameters.slice(0, firstInitParamIdx); hasValidParameters = this.visitParameterList(requiredParams, namesOnly); } if (firstInitParamIdx !== parameters.length) { if (hasValidParameters) this.emitNoSpace(','); let positionalOptional = parameters.slice(firstInitParamIdx, parameters.length); if (!namesOnly) { this.emit('['); } this.visitParameterList(positionalOptional, namesOnly); if (!namesOnly) { this.emitNoSpace(']'); } } this.emitNoSpace(')'); } }
the_stack
import React from 'react' import { FormComponentProps } from 'antd/lib/form' import { Form, Input, Select, Button, Row, Col, Menu, Tabs } from 'antd' const FormItem = Form.Item const Option = Select.Option const Search = Input.Search const TabPane = Tabs.TabPane import { uuid } from 'utils/util' const codeMirror = require('codemirror/lib/codemirror') const utilStyles = require('assets/less/util.less') import sqlFunctions from 'assets/sqlFunctionName/sqlFns' import 'codemirror/lib/codemirror.css' import 'assets/override/codemirror_theme.css' require('codemirror/mode/javascript/javascript') import 'codemirror/addon/lint/lint.css' require('codemirror/addon/hint/javascript-hint') require('codemirror/addon/lint/json-lint') require('codemirror/addon/lint/css-lint') require('codemirror/addon/lint/lint') require('codemirror/addon/lint/javascript-lint') require('codemirror/addon/lint/json-lint') require('codemirror/addon/lint/css-lint') const styles = require('../Widget.less') interface IComputedConfigFormProps { form: any, onSave: (obj: any) => void, onClose: () => void, categories: any, queryInfo: any selectedComputed: object } interface IComputedConfigFormStates { variableNumber: number categories: any filterFunction: string queryInfo: string[] } export class ComputedConfigForm extends React.Component<IComputedConfigFormProps & FormComponentProps, IComputedConfigFormStates> { private Editor: any constructor(props) { super(props) this.state = { variableNumber: 1, queryInfo: [], categories: [], filterFunction: '' } this.Editor = false } public componentWillMount() { const { queryInfo, categories } = this.props this.setState({ queryInfo, categories }) } public componentDidMount() { const queryTextarea = document.querySelector('#sql_tmpl') this.handleTmplCodeMirror(queryTextarea) } public componentWillReceiveProps(nextProps) { const { selectedComputed } = nextProps if (selectedComputed && selectedComputed.sqlExpression) { this.Editor.doc.setValue(selectedComputed.sqlExpression) } else { this.Editor.doc.setValue('') } } private customDvSqlMode = () => { const { categories, queryInfo } = this.props const highLightFields = categories.map((cate) => `${cate.name}`) const hightLightQuery = [...queryInfo] codeMirror.defineMode('dvSqlMode', (e, t) => { function r(t, r) { const o = t.next() if (p[o]) { const i = p[o](t, r, '{' === o ? hightLightQuery : highLightFields) if (i !== !1) { return i } } if ((1 == m.nCharCast && ("n" == o || "N" == o) || 1 == m.charsetCast && "_" == o && t.match(/[a-z][a-z0-9]*/i)) && ("'" == t.peek() || '"' == t.peek())) return "keyword"; if (/^[\(\),\;\[\]\{\}]/.test(o)) return null; if ("." != o) { if (d.test(o)) return t.eatWhile(d), "operator"; if ("{" == o && (t.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || t.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) return "number"; t.eatWhile(/^[_\w\d]/); const h = t.current().toLowerCase(); return f.hasOwnProperty(h) && (t.match(/^( )+'[^']*'/) || t.match(/^( )+"[^"]*"/)) ? "number" : l.hasOwnProperty(h) ? "atom" : u.hasOwnProperty(h) ? "keyword" : c.hasOwnProperty(h) ? "builtin" : s.hasOwnProperty(h) ? "string-2" : null } } function o(e, t, r) { t.context = { prev: t.context, indent: e.indentation(), col: e.column(), type: r } } function i(e) { e.indent = e.context.indent, e.context = e.context.prev } const s = t.client || {} const l = t.atoms || { false: !0, true: !0, null: !0 } const c = t.builtin || {} const u = t.keywords || {} const d = t.operatorChars || /^[\/\*\+\-%<>!=&|~^]/ const m = t.support || {} const p = t.hooks || {} const f = t.dateSQL || { date: !0, time: !0, timestamp: !0 } return { startState: () => { return { tokenize: r, context: null } }, token: (e, t) => { if (e.sol() && t.context && null == t.context.align && (t.context.align = !1), e.eatSpace()) { return null } const r = t.tokenize(e, t) if ('comment' === r) { return r } t.context && null == t.context.align && (t.context.align = !0) const n = e.current() return "(" == n ? o(e, t, ")") : "[" == n ? o(e, t, "]") : t.context && t.context.type == n && i(t), r } } }) function n(e, t, r) { for (var n, a = ""; null != (n = e.next());) { if ("]" == n && !e.eat("]")) return r && r.indexOf(a) < 0 ? "error" : "variable-2"; a += n } return null } function a(e, t, r) { for (var n, a = ""; null != (n = e.next());) { if ("}" == n && !e.eat("}")) return r && r.indexOf(a) < 0 ? "error" : "variable-2"; a += n } return null } function s(e) { for (var t = {}, r = e.split(" "), n = 0; n < r.length; ++n) t[r[n]] = !0; return t } const l = 'sum avg count max min median stddev stdev_pop stddev_samp var_pop var_samp variance percentiles percentile_cont percentile_disc' codeMirror.defineMIME('text/x-dv-sql-mode', { name: 'dvSqlMode', keywords: s(l), hooks: { '[': n, '{': a } }) const hintList = sqlFunctions.map((fn) => fn.name).concat(categories.map((cate) => cate.name)).concat(queryInfo) codeMirror.registerHelper('hint', 'dvSqlMode', (cm) => { const cur = cm.getCursor() const token = cm.getTokenAt(cur) const start = token.start const end = cur.ch const str = token.string const list = hintList.filter((item) => { return item.indexOf(str) === 0 }) if (list.length) { return { list, from: codeMirror.Pos(cur.line, start), to: codeMirror.Pos(cur.line, end) } } }) } private handleTmplCodeMirror = (queryWrapperDOM) => { this.customDvSqlMode() if (!this.Editor) { this.Editor = codeMirror.fromTextArea(queryWrapperDOM, { mode: 'text/x-dv-sql-mode', theme: '3024-day', width: '100%', height: '80px', lineNumbers: true, lineWrapping: true, autoCloseBrackets: true, matchBrackets: true, foldGutter: true, gutters: ['CodeMirror-lint-markers', 'CodeMirror-linenumbers', 'CodeMirror-foldgutter'] }) this.Editor.addKeyMap({ 'name': 'autoInsertParentheses', "'('": (cm) => { const cur = cm.getCursor() cm.replaceRange('()', cur, cur, '+insert') cm.doc.setCursor({ line: cur.line, ch: cur.ch + 1 }) }, "'['": (cm) => { const cur = cm.getCursor() cm.replaceRange('[]', cur, cur, '+insert') cm.doc.setCursor({ line: cur.line, ch: cur.ch + 1 }) }, "'{'": (cm) => { const cur = cm.getCursor() cm.replaceRange('{}', cur, cur, '+insert') cm.doc.setCursor({ line: cur.line, ch: cur.ch + 1 }) } }) this.Editor.on('change', function (editor, change) { if (change.origin === '+input') { const text = change.text setTimeout(function () { editor.execCommand('autocomplete') }, 50) } }) } } private saveComputed = () => { this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { const { selectedComputed } = this.props const sqlExpression = this.Editor.doc.getValue() const { id, name, visualType } = this.props.form.getFieldsValue() console.log({ id }) console.log({ selectedComputed }) this.props.onSave({ id: id ? id : uuid(8, 16), name, visualType, sqlExpression, title: 'computedField', from: selectedComputed ? selectedComputed['from'] : '' }) this.closePanel() } }) } private closePanel = () => { this.resetForm() this.props.onClose() } private resetForm = () => { this.Editor.doc.setValue('') this.props.form.resetFields() } private filterFunction = (value) => { this.setState({ filterFunction: value }) } private filterModel = (value) => { this.setState({ categories: this.props.categories.filter((cate) => { return cate.name.indexOf(value) >= 0 }) }) } private filterQuery = (value) => { this.setState({ queryInfo: this.props.queryInfo.filter((query) => { return query.indexOf(value) >= 0 }) }) } private triggerMenuItem = (params) => ({ item, key, keyPath }) => { const defaultValue = this.Editor.doc.getValue() let currentValue = '' switch (params) { case 'fn': currentValue = `${defaultValue}${key}()` break case 'category': currentValue = `${defaultValue}[${key}]` break case 'query': currentValue = `${defaultValue}{${key}}` break default: break } this.Editor.doc.setValue(currentValue) } public render() { const { form } = this.props const { queryInfo, categories, variableNumber, filterFunction } = this.state const { getFieldDecorator } = form const controlTypeOptions = [ { text: '文本', value: 'string' }, { text: '数值', value: 'number' }, { text: '日期', value: 'date' } ].map((o) => ( <Option key={o.value} value={o.value}>{o.text}</Option> )) const functions = sqlFunctions.filter((func) => { return func.name.indexOf(filterFunction.toUpperCase()) >= 0 }) const functionSelectMenu = ( <Menu onClick={this.triggerMenuItem('fn')}> {functions && functions.length ? functions.map((d, index) => <Menu.Item key={`${d.name}`}> <a target="_blank" rel="noopener noreferrer" href="javascript:;">{d.name}</a> </Menu.Item> ) : []} </Menu> ) const modelSelectMenu = ( <Menu onClick={this.triggerMenuItem('category')}> {categories && categories.length ? categories.map((d, index) => <Menu.Item key={`${d.name}`}> <a target="_blank" rel="noopener noreferrer" href="javascript:;">{d.name}</a> </Menu.Item> ) : []} </Menu> ) const querySelectMenu = ( <Menu onClick={this.triggerMenuItem('query')}> {queryInfo && queryInfo.length ? queryInfo.map((query, index) => <Menu.Item key={`${query}`}> <a target="_blank" rel="noopener noreferrer" href="javascript:;">{query}</a> </Menu.Item> ) : []} </Menu> ) return ( <div className={styles.computedConfigForm}> <div className={styles.body}> <div className={styles.fields}> <div className={styles.fieldName}> <Form> <Row gutter={8}> <Col span={12}> <FormItem className={utilStyles.hide}> {getFieldDecorator('id', {})( <Input /> )} </FormItem> <FormItem> {getFieldDecorator('name', { rules: [{ required: true, message: '计算字段名称不能为空' }] })( <Input placeholder="计算字段名称" /> )} </FormItem> </Col> <Col span={12} key="visualType"> <FormItem> {getFieldDecorator('visualType', { rules: [{ required: true, message: '计算字段类型不能为空' }] })( <Select placeholder="计算字段类型"> {controlTypeOptions} </Select> )} </FormItem> </Col> </Row> </Form> </div> <div className={styles.tmplWrapper}> <textarea id="sql_tmpl" placeholder="输入SQL语句" /> </div> </div> <div className={styles.options}> <div className={styles.cardContainer}> <Tabs defaultActiveKey="functions" size="small" tabPosition="right"> <TabPane tab="函数" key="functions"> <div className={styles.menuWrapper}> <Search placeholder="Search the function" onSearch={this.filterFunction} /> {functionSelectMenu} </div> </TabPane> <TabPane tab="字段" key="model"> <div className={styles.menuWrapper}> <Search placeholder="Search the function" onSearch={this.filterModel} /> {modelSelectMenu} </div> </TabPane> <TabPane tab="变量" key="query"> <div className={styles.menuWrapper}> <Search placeholder="Search the function" onSearch={this.filterQuery} /> {querySelectMenu} </div> </TabPane> </Tabs> </div> </div> </div> <div className={styles.footer}> <div className={styles.foot}> <Button onClick={this.closePanel}>取消</Button> <Button type="primary" onClick={this.saveComputed}>保存</Button> </div> </div> </div> ) } } export default Form.create<IComputedConfigFormProps & FormComponentProps>()(ComputedConfigForm)
the_stack
import { deepEqual } from '@gravitee/ui-components/src/lib/utils'; export enum Scope { API, APPLICATION, PLATFORM, } export enum ConditionType { STRING = 'STRING', THRESHOLD = 'THRESHOLD', THRESHOLD_RANGE = 'THRESHOLD_RANGE', RATE = 'RATE', FREQUENCY = 'FREQUENCY', THRESHOLD_ACCUMULATE = 'THRESHOLD_ACCUMULATE', COMPARE = 'COMPARE', STRING_COMPARE = 'STRING_COMPARE', } class Operator { key: string; name: string; constructor(key: string, name: string) { this.key = key; this.name = name; } } export class Tuple { key: string; value: string; constructor(key: string, value: string) { this.key = key; this.value = value; } } export abstract class Metrics { key: string; name: string; conditions: string[]; loader: (type: number, id: string, $injector: any) => Tuple[]; scopes: Scope[]; supportPropertyProjection = false; static filterByScope(metrics: Metrics[], scope: Scope): Metrics[] { return metrics.filter((metric) => metric.scopes === undefined || metric.scopes.indexOf(scope) !== -1); } constructor( key: string, name: string, conditions: string[], supportPropertyProjection?: boolean, scopes?: Scope[], loader?: (type: number, id: string, $injector: any) => Tuple[], ) { this.key = key; this.name = name; this.conditions = conditions; this.supportPropertyProjection = supportPropertyProjection; this.scopes = scopes; this.loader = loader; } } export class Alert { id: string; name: string; severity: string; source: string; description: string; type: string; reference_type: Scope; reference_id: string; enabled: boolean; dampening: Dampening; conditions: any[]; projections: any[]; notifications: any[]; filters: any[]; template: boolean; event_rules: any; notificationPeriods: Array<Period>; constructor( name: string, severity: string, source: string, description: string, type: string, reference_type: Scope, reference_id: string, ) { this.name = name; this.severity = severity; this.source = source; this.description = description; this.type = type; this.reference_type = reference_type; this.reference_id = reference_id; } } export class Dampening { mode: string; evaluations: number; total: number; duration: number; } export class DampeningMode { static STRICT_COUNT = new DampeningMode('STRICT_COUNT', 'N consecutive true evaluations'); static RELAXED_COUNT = new DampeningMode('RELAXED_COUNT', 'N true evaluations out of M total evaluations'); static RELAXED_TIME = new DampeningMode('RELAXED_TIME', 'N true evaluations in T time'); static STRICT_TIME = new DampeningMode('STRICT_TIME', 'Only true evaluations for at least T time'); static MODES: DampeningMode[] = [ DampeningMode.STRICT_COUNT, DampeningMode.RELAXED_COUNT, DampeningMode.RELAXED_TIME, DampeningMode.STRICT_TIME, ]; public type: string; public description: string; constructor(type: string, description: string) { this.type = type; this.description = description; } } export abstract class Condition { type: string; name: string; protected constructor(type: string, name: string) { this.type = type; this.name = name; } abstract getOperators(): Operator[]; } export class ThresholdCondition extends Condition { static TYPE = 'THRESHOLD'; static LT: Operator = new Operator('LT', 'less than'); static LTE: Operator = new Operator('LTE', 'less than or equals to'); static GTE: Operator = new Operator('GTE', 'greater than or equals to'); static GT: Operator = new Operator('GT', 'greater than'); static OPERATORS: Operator[] = [ThresholdCondition.LT, ThresholdCondition.LTE, ThresholdCondition.GTE, ThresholdCondition.GT]; constructor() { super(ThresholdCondition.TYPE, 'Threshold'); } getOperators(): Operator[] { return ThresholdCondition.OPERATORS; } } export class RateCondition extends Condition { static TYPE = 'RATE'; static LT: Operator = new Operator('LT', 'less than'); static LTE: Operator = new Operator('LTE', 'less than or equals to'); static GTE: Operator = new Operator('GTE', 'greater than or equals to'); static GT: Operator = new Operator('GT', 'greater than'); static OPERATORS: Operator[] = [RateCondition.LT, RateCondition.LTE, RateCondition.GTE, RateCondition.GT]; constructor() { super(RateCondition.TYPE, 'Rate'); } getOperators(): Operator[] { return RateCondition.OPERATORS; } } export class FrequencyCondition extends Condition { static TYPE = 'FREQUENCY'; static LT: Operator = new Operator('LT', 'less than'); static LTE: Operator = new Operator('LTE', 'less than or equals to'); static GTE: Operator = new Operator('GTE', 'greater than or equals to'); static GT: Operator = new Operator('GT', 'greater than'); static OPERATORS: Operator[] = [FrequencyCondition.LT, FrequencyCondition.LTE, FrequencyCondition.GTE, FrequencyCondition.GT]; constructor() { super(FrequencyCondition.TYPE, 'Frequency'); } getOperators(): Operator[] { return FrequencyCondition.OPERATORS; } } class Function { key: string; name: string; constructor(key: string, name: string) { this.key = key; this.name = name; } } export class AggregationCondition extends Condition { static TYPE = 'AGGREGATION'; static LT: Operator = new Operator('LT', 'less than'); static LTE: Operator = new Operator('LTE', 'less than or equals to'); static GTE: Operator = new Operator('GTE', 'greater than or equals to'); static GT: Operator = new Operator('GT', 'greater than'); static OPERATORS: Operator[] = [AggregationCondition.LT, AggregationCondition.LTE, AggregationCondition.GTE, AggregationCondition.GT]; // This is our custom Function type // eslint-disable-next-line @typescript-eslint/ban-types static FUNCTIONS: Function[] = [ new Function('count', 'count'), new Function('avg', 'average'), new Function('min', 'min'), new Function('max', 'max'), new Function('p50', '50th percentile'), new Function('p90', '90th percentile'), new Function('p95', '95th percentile'), new Function('p99', '99th percentile'), ]; constructor() { super(AggregationCondition.TYPE, 'Aggregation'); } getOperators(): Operator[] { return AggregationCondition.OPERATORS; } } export class ThresholdRangeCondition extends Condition { static TYPE = 'THRESHOLD_RANGE'; static BETWEEN: Operator = new Operator('BETWEEN', 'between'); static OPERATORS: Operator[] = [ThresholdRangeCondition.BETWEEN]; constructor() { super(ThresholdRangeCondition.TYPE, 'Threshold Range'); } getOperators(): Operator[] { return ThresholdRangeCondition.OPERATORS; } } export class CompareCondition extends Condition { static TYPE = 'COMPARE'; static LT: Operator = new Operator('LT', 'less than'); static LTE: Operator = new Operator('LTE', 'less than or equals to'); static GTE: Operator = new Operator('GTE', 'greater than or equals to'); static GT: Operator = new Operator('GT', 'greater than'); static OPERATORS: Operator[] = [CompareCondition.LT, CompareCondition.LTE, CompareCondition.GTE, CompareCondition.GT]; constructor() { super(CompareCondition.TYPE, 'Compare'); } getOperators(): Operator[] { return CompareCondition.OPERATORS; } } export class StringCondition extends Condition { static TYPE = 'STRING'; static EQUALS: Operator = new Operator('EQUALS', 'equals to'); static NOT_EQUALS: Operator = new Operator('NOT_EQUALS', 'not equals to'); static STARTS_WITH: Operator = new Operator('STARTS_WITH', 'starts with'); static ENDS_WITH: Operator = new Operator('ENDS_WITH', 'ends with'); static CONTAINS: Operator = new Operator('CONTAINS', 'contains'); static MATCHES: Operator = new Operator('MATCHES', 'matches'); static OPERATORS: Operator[] = [ StringCondition.EQUALS, StringCondition.NOT_EQUALS, StringCondition.STARTS_WITH, StringCondition.ENDS_WITH, StringCondition.CONTAINS, StringCondition.MATCHES, ]; constructor() { super(StringCondition.TYPE, 'String'); } getOperators(): Operator[] { return StringCondition.OPERATORS; } } export class StringCompareCondition extends Condition { static TYPE = 'STRING_COMPARE'; static EQUALS: Operator = new Operator('EQUALS', 'equals to'); static NOT_EQUALS: Operator = new Operator('NOT_EQUALS', 'not equals to'); static STARTS_WITH: Operator = new Operator('STARTS_WITH', 'starts with'); static ENDS_WITH: Operator = new Operator('ENDS_WITH', 'ends with'); static CONTAINS: Operator = new Operator('CONTAINS', 'contains'); static MATCHES: Operator = new Operator('MATCHES', 'matches'); static OPERATORS: Operator[] = [ StringCompareCondition.EQUALS, StringCompareCondition.NOT_EQUALS, StringCompareCondition.STARTS_WITH, StringCompareCondition.ENDS_WITH, StringCompareCondition.CONTAINS, StringCompareCondition.MATCHES, ]; constructor() { super(StringCompareCondition.TYPE, 'String Compare'); } getOperators(): Operator[] { return StringCompareCondition.OPERATORS; } } export class DurationTimeUnit { static SECONDS: DurationTimeUnit = new DurationTimeUnit('SECONDS', 'Seconds'); static MINUTES: DurationTimeUnit = new DurationTimeUnit('MINUTES', 'Minutes'); static HOURS: DurationTimeUnit = new DurationTimeUnit('HOURS', 'Hours'); static TIME_UNITS: DurationTimeUnit[] = [DurationTimeUnit.SECONDS, DurationTimeUnit.MINUTES, DurationTimeUnit.HOURS]; key: string; name: string; constructor(key: string, name: string) { this.key = key; this.name = name; } } export class Conditions { static THRESHOLD: Condition = new ThresholdCondition(); static THRESHOLD_RANGE: Condition = new ThresholdRangeCondition(); static STRING: Condition = new StringCondition(); static RATE: Condition = new RateCondition(); static FREQUENCY: Condition = new FrequencyCondition(); static COMPARE: Condition = new CompareCondition(); static STRING_COMPARE: Condition = new StringCompareCondition(); static CONDITIONS: Condition[] = [ Conditions.THRESHOLD, Conditions.THRESHOLD_RANGE, Conditions.STRING, Conditions.RATE, Conditions.FREQUENCY, Conditions.COMPARE, Conditions.STRING_COMPARE, ]; static findByType(type: string): Condition { return Conditions.CONDITIONS.find((condition) => condition.type === type); } } export class Period { days: Array<number>; beginHour: number; endHour: number; zoneId: string; constructor(param: { days: Array<number>; beginHour: number; endHour: number; zoneId: string }) { this.days = param.days; this.beginHour = param.beginHour; this.endHour = param.endHour; this.zoneId = param.zoneId; } equals({ days, beginHour, endHour }) { return deepEqual(days, this.days, true) && this.beginHour === beginHour && this.endHour === endHour; } }
the_stack
import { Component } from '@angular/core'; import { IonicPage, NavParams, LoadingController, MenuController } from 'ionic-angular'; import { AlertController, ToastController } from 'ionic-angular'; import { BrowserTab } from '@ionic-native/browser-tab'; import { InAppBrowser } from '@ionic-native/in-app-browser'; import { SteemiaProvider } from 'providers/steemia/steemia'; import { SteeemActionsProvider } from 'providers/steeem-actions/steeem-actions'; import { CryptoProvider } from 'providers/crypto-api/crypto-api'; import { Address } from 'models/models'; import { TranslateService } from '@ngx-translate/core'; /** * * @author Hüseyin TERKİR * @author Jayser Mendez * @version 2.0 */ @IonicPage() @Component({ selector: 'page-wallet', templateUrl: 'wallet.html', }) export class WalletPage { // Main Account Data private account_balance: { sbd?: any, balance?: any, vesting_shares?: any } = {}; // Rewards Data private rewards = { steem: null, sbd: null, vesting_steem: null, vesting_steem_balance: null }; // Account Addresses Data private address = { btc: { address: null, confirmed: null, unconfirmed: null }, ltc: { address: null, confirmed: null, unconfirmed: null }, eth: { address: null, confirmed: null, unconfirmed: null } }; // Coin's Prices private prices: any; private account: string = "steemia-io"; constructor(public navParams: NavParams, public alertCtrl: AlertController, private toastCtrl: ToastController, public menu: MenuController, private translate: TranslateService, private loadingCtrl: LoadingController, private steeemActions: SteeemActionsProvider, private steemiaProvider: SteemiaProvider, private browserTab: BrowserTab, private iab: InAppBrowser, private cryptoProvider: CryptoProvider) {} ionViewDidLoad() { this.account = this.navParams.get("author"); this.getAccount().then(() => { // Conditions to avoid querying not necessary data. if (this.address.btc.address !== null || this.address.btc.address !== undefined) { this.checkBalance('btc'); } if (this.address.eth.address !== null || this.address.eth.address !== undefined) { this.checkBalance('eth'); } if (this.address.ltc.address !== null || this.address.ltc.address !== undefined) { this.checkBalance('ltc'); } this.cryptoProvider.get_prices().then(prices => { this.prices = prices; }); }); } ionViewDidEnter() { this.menu.enable(false); } ionViewWillLeave() { this.menu.enable(true); } /** * Method to transfer coins * @param coin */ showPrompt(coin) { let prompt = this.alertCtrl.create({ title: this.translate.instant('pages.wallet.prompts.transfer.title'), subTitle: this.translate.instant('pages.wallet.prompts.transfer.subtitle'), message: this.translate.instant('pages.wallet.prompts.transfer.message'), cssClass: 'alert-center', enableBackdropDismiss: true, inputs: [{ name: 'username', placeholder: this.translate.instant('pages.wallet.prompts.transfer.inputs.recipient'), }, { name: 'amount', placeholder: this.translate.instant('pages.wallet.prompts.transfer.inputs.amount'), }, { name: 'memo', placeholder: this.translate.instant('pages.wallet.prompts.transfer.inputs.memo'), }], buttons: [{ text: this.translate.instant('generic_messages.cancel'), cssClass: 'block round dark ion-button' }, { text: this.translate.instant('pages.wallet.prompts.transfer.send'), handler: data => { if(!data.username) { let toast = this.toastCtrl.create({ message: 'Username field cannot be empty!', duration: 3000, position: 'top' }); toast.present(); } else if(!data.amount) { let toast = this.toastCtrl.create({ message: 'Amount field cannot be empty!', duration: 3000, position: 'top' }); toast.present(); } else { this.browserTab.isAvailable() .then((isAvailable: boolean) => { if (isAvailable) { this.browserTab.openUrl('https://steemconnect.com/sign/transfer?to=' + data.username + '&amount=' + data.amount + '%20' + coin + '&memo=' + data.memo); } else { // if custom tabs are not available you may use InAppBrowser } }); } } } ] }); prompt.present(); } /** * Method to add a new crypto address */ private addAddress() { let prompt = this.alertCtrl.create({ title: this.translate.instant('pages.wallet.prompts.add_crypto.title'), message: this.translate.instant('pages.wallet.prompts.add_crypto.message'), inputs: [{ type: 'radio', label: 'Bitcoin', value: 'bitcoin' }, { type: 'radio', label: 'Ethereum', value: 'ethereum' }, { type: 'radio', label: 'Litecoin', value: 'litecoin' }], buttons: [{ text: this.translate.instant('generic_messages.cancel'), }, { text: this.translate.instant('pages.wallet.prompts.add_crypto.continue'), handler: data => { this.SaveAdress(data); } }] }); prompt.present(); } /** * Method to save a new crypto address * @param coin */ private SaveAdress(coin): void { let alert = this.alertCtrl.create({ title: this.translate.instant('pages.wallet.prompts.save_address.title', { coin: coin }), inputs: [{ name: 'address', placeholder: this.translate.instant('pages.wallet.prompts.save_address.inputs.address', { coin: coin }), }], buttons: [{ text: this.translate.instant('generic_messages.cancel'), role: 'cancel' }, { text: this.translate.instant('pages.wallet.prompts.save_address.save'), handler: data => { this.browserTab.isAvailable() .then((isAvailable: boolean) => { if (isAvailable) { this.browserTab.openUrl(`https://steemconnect.com/sign/profile-update?${coin}=${data.address}`); } else { // if custom tabs are not available you may use InAppBrowser } }); } } ] }); alert.present(); } /** * Method to get account data */ private getAccount() { let loading = this.loadingCtrl.create({ content: 'Please wait...', dismissOnPageChange: true, showBackdrop: true, enableBackdropDismiss: true }); loading.present(); return new Promise(resolve => { this.steemiaProvider.dispatch_account(this.account).then(data => { const metadata = JSON.parse(data[0].json_metadata); this.account_balance = { sbd: parseFloat(data[0].sbd_balance), balance: parseFloat(data[0].balance), vesting_shares: parseInt(data[0].vesting_shares).toFixed(2) } this.rewards = { sbd: parseFloat(data[0].reward_sbd_balance), steem: parseFloat(data[0].reward_steem_balance), vesting_steem: parseFloat(data[0].reward_vesting_balance), vesting_steem_balance: parseFloat(data[0].reward_vesting_steem) } if (metadata.profile.bitcoin) { this.address.btc.address = metadata.profile.bitcoin; } if (metadata.profile.litecoin) { this.address.ltc.address = metadata.profile.litecoin; } if (metadata.profile.ethereum) { this.address.eth.address = metadata.profile.ethereum; } }).then(() => { resolve(); loading.dismiss(); }); }) } /** * Event listener for the wallet item component * @param {Object} event */ private eventListener(event) { if (event.type === 'transfer') { this.showPrompt(event.name) } else if (event.type === 'buy') { switch (event.name) { case 'STEEM': this.buySteem(); break; case 'SBD': this.buySbd(); break; case 'Bitcoin': this.buy_crypto('btc'); break; case 'Litecoin': this.buy_crypto('ltc'); break; case 'Ethereum': this.buy_crypto('eth'); break; } } else if (event.type === 'sell') { switch (event.name) { case 'STEEM': this.sell('steem'); break; case 'SBD': this.sell('sbd'); break; case 'Bitcoin': this.sell('btc'); break; case 'Litecoin': this.sell('ltc'); break; case 'Ethereum': this.sell('eth'); break; } } } /** * Method to check account balance * @param {String} type */ private checkBalance(type: string): void { this.cryptoProvider.check_balance(type, this.address[type].address).then((data: any) => { this.address[type].confirmed = data.confirmed; this.address[type].unconfirmed = data.unconfirmed; }); } /** * Method to sell cryptos * @param {String} type */ private sell(type: string): void { this.cryptoProvider.buy_sell(this.account_balance[type], this.address.btc.address, type, 'btc'); } /** * Method to buy cryptos * @param {String} type */ private buy_crypto(type: string): void { this.cryptoProvider.buy_sell(this.account_balance.sbd, this.address[type].address, 'sbd', type); } /** * Method to buy Steem */ private buySteem(): void { this.cryptoProvider.buy_sell(1, this.account, 'btc', 'steem'); } /** * Method to buy SBD */ private buySbd(): void { this.cryptoProvider.buy_sell(1, this.account, 'btc', 'sbd'); } /** * Method to claim rewards */ private claim_rewards(): void { const steem = this.rewards.steem.toFixed(3).toString() + ' STEEM'; const sbd = this.rewards.sbd.toFixed(3).toString() + ' SBD'; const sp = this.rewards.vesting_steem.toFixed(6).toString() + ' VESTS'; let loader = this.loadingCtrl.create({ content: this.translate.instant('generic_messages.collecting_rewards') }); loader.present(); this.steeemActions.dispatch_claim_reward(steem, sbd, sp).then(data => { loader.dismiss(); this.getAccount(); let toast = this.toastCtrl.create({ message: this.translate.instant('generic_messages.rewards_collected'), duration: 1500 }); toast.present(); }); } }
the_stack
import { tickStep } from './ticks'; type FormatType = '' | '%' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'o' | 'p' | 'r' | 's' | 'X' | 'x'; function formatDefault(x: number, p?: number): string { const xs = x.toPrecision(p); out: for (var n = xs.length, i = 1, i0 = -1, i1 = 0; i < n; ++i) { switch (xs[i]) { case '.': i0 = i1 = i; break; case '0': if (i0 === 0) i0 = i; i1 = i; break; case 'e': break out; default: if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? xs.slice(0, i0) + xs.slice(i1 + 1) : xs; } const formatTypes: { [key in FormatType]: (x: number, p?: number) => string } = { '': formatDefault, // Multiply by 100, and then decimal notation with a percent sign. '%': (x: number, p?: number): string => (x * 100).toFixed(p), // Binary notation, rounded to integer. 'b': (x: number) => Math.round(x).toString(2), // Converts the integer to the corresponding unicode character before printing. 'c': (x: number) => String(x), // Decimal notation, rounded to integer. 'd': formatDecimal, // Exponent notation. 'e': (x: number, p?: number) => x.toExponential(p), // Fixed point notation. 'f': (x: number, p?: number) => x.toFixed(p), // Either decimal or exponent notation, rounded to significant digits. 'g': (x: number, p?: number) => x.toPrecision(p), // Octal notation, rounded to integer. 'o': (x: number) => Math.round(x).toString(8), // Multiply by 100, round to significant digits, and then decimal notation with a percent sign. 'p': (x: number, p?: number) => formatRounded(x * 100, p), // Decimal notation, rounded to significant digits. 'r': formatRounded, // Decimal notation with a SI prefix, rounded to significant digits. 's': formatPrefixAuto, // Hexadecimal notation, using upper-case letters, rounded to integer. 'X': (x: number) => Math.round(x).toString(16).toUpperCase(), // Hexadecimal notation, using lower-case letters, rounded to integer. 'x': (x: number) => Math.round(x).toString(16) }; const prefixes = ['y', 'z', 'a', 'f', 'p', 'n', '\xB5', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; interface FormatSpecifierOptions { fill?: string; align?: string; sign?: string; symbol?: string; zero?: string; width?: string; comma?: string; precision?: string; trim?: string; type?: FormatType; string?: string; } /** * [[fill]align][sign][#][0][width][grouping_option][.precision][type] */ export class FormatSpecifier { /** * Can be any character. */ fill: string; /** * `>` - Forces the field to be right-aligned within the available space (default). * `<` - Forces the field to be left-aligned within the available space. * `^` - Forces the field to be centered within the available space. * `=` - Like >, but with any sign and symbol to the left of any padding. */ align: string; /** * `-` - Nothing for zero or positive and a minus sign for negative (default). * `+` - A plus sign for zero or positive and a minus sign for negative. * `(` - Nothing for zero or positive and parentheses for negative. * ` ` - A space for zero or positive and a minus sign for negative. */ sign: string; /** * `$` - Apply currency symbols per the locale definition. * `#` - For binary, octal, or hexadecimal notation, prefix by `0b`, `0o`, or `0x`, respectively. */ symbol: string; /** * The `0` option enables zero-padding. Implicitly sets fill to `0` and align to `=`. */ zero: boolean; /** * The width defines the minimum field width. * If not specified, then the width will be determined by the content. */ width?: number; /** * The comma `,` option enables the use of a group separator, such as a comma for thousands. */ comma: boolean; /** * Depending on the type, the precision either indicates the number of digits * that follow the decimal point (types `f` and `%`), or the number of significant digits (types ` `​, `e`, `g`, `r`, `s` and `p`). * If the precision is not specified, it defaults to 6 for all types except `​ ` (none), which defaults to 12. * Precision is ignored for integer formats (types `b`, `o`, `d`, `x`, `X` and `c`). */ precision?: number; /** * The `~` option trims insignificant trailing zeros across all format types. * This is most commonly used in conjunction with types `r`, `e`, `s` and `%`. */ trim: boolean; /** * Presentation style. */ type: FormatType | ''; /** * Interpolation string. */ string?: string; constructor(specifier: FormatSpecifierOptions | FormatSpecifier) { if (specifier instanceof FormatSpecifier) { this.fill = specifier.fill; this.align = specifier.align; this.sign = specifier.sign; this.symbol = specifier.symbol; this.zero = specifier.zero; this.width = specifier.width; this.comma = specifier.comma; this.precision = specifier.precision; this.trim = specifier.trim; this.type = specifier.type; this.string = specifier.string; } else { this.fill = specifier.fill === undefined ? ' ' : String(specifier.fill); this.align = specifier.align === undefined ? '>' : String(specifier.align); this.sign = specifier.sign === undefined ? '-' : String(specifier.sign); this.symbol = specifier.symbol === undefined ? '' : String(specifier.symbol); this.zero = !!specifier.zero; this.width = specifier.width === undefined ? undefined : +specifier.width; this.comma = !!specifier.comma; this.precision = specifier.precision === undefined ? undefined : +specifier.precision; this.trim = !!specifier.trim; this.type = specifier.type === undefined ? '' : String(specifier.type) as FormatType; this.string = specifier.string; } } } // [[fill]align][sign][symbol][0][width][,][.precision][~][type] const formatRegEx = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i; const interpolateRegEx = /(#\{(.*?)\})/g; export function makeFormatSpecifier(specifier: string | FormatSpecifier): FormatSpecifier { if (specifier instanceof FormatSpecifier) { return new FormatSpecifier(specifier); } let found = false; let string = specifier.replace(interpolateRegEx, function () { if (!found) { specifier = arguments[2]; found = true; } return '#{}'; }); const match = formatRegEx.exec(specifier); if (!match) { throw new Error(`Invalid format: ${specifier}`); } return new FormatSpecifier({ fill: match[1], align: match[2], sign: match[3], symbol: match[4], zero: match[5], width: match[6], comma: match[7], precision: match[8] && match[8].slice(1), trim: match[9], type: match[10] as FormatType, string: found ? string : undefined }); } export function tickFormat(start: number, stop: number, count: number, specifier?: string): (n: number | { valueOf(): number }) => string { const step = tickStep(start, stop, count); const formatSpecifier = makeFormatSpecifier(specifier == undefined ? ',f' : specifier); let precision: number; switch (formatSpecifier.type) { case 's': { const value = Math.max(Math.abs(start), Math.abs(stop)); if (formatSpecifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) { formatSpecifier.precision = precision; } return formatPrefix(formatSpecifier, value); } case '': case 'e': case 'g': case 'p': case 'r': { if (formatSpecifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) { formatSpecifier.precision = precision - +(formatSpecifier.type === 'e'); } break; } case 'f': case '%': { if (formatSpecifier.precision == null && !isNaN(precision = precisionFixed(step))) { formatSpecifier.precision = precision - +(formatSpecifier.type === '%') * 2; } break; } } return format(formatSpecifier); } let prefixExponent: number; function formatPrefixAuto(x: number, p: number = 0) { const d = formatDecimalParts(x, p); if (!d) { return String(x); } const coefficient = d[0]; const exponent = d[1]; prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3; const i = exponent - prefixExponent + 1; const n = coefficient.length; if (i === n) { return coefficient; } else { if (i > n) { return coefficient + new Array(i - n + 1).join('0'); } if (i > 0) { return coefficient.slice(0, i) + '.' + coefficient.slice(i); } else { const parts = formatDecimalParts(x, Math.max(0, p + i - 1)); return '0.' + new Array(1 - i).join('0') + parts![0]; // less than 1y! } } } function formatDecimal(x: number): string { return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString('en').replace(/,/g, '') : x.toString(10); } function formatGroup(grouping: number[], thousands: string): (value: string, width: number) => string { return (value, width) => { const t: string[] = []; let i = value.length; let j = 0; let g = grouping[0]; let length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) { g = Math.max(1, width - length); } t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) { break; } g = grouping[j = (j + 1) % grouping.length]; } return t.reverse().join(thousands); }; } export function formatNumerals(numerals: string[]): (value: string) => string { return value => value.replace(/[0-9]/g, i => numerals[+i]); } // Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k. function formatTrim(s: string): string { out: for (var n = s.length, i = 1, i0 = -1, i1 = 0; i < n; ++i) { switch (s[i]) { case '.': i0 = i1 = i; break; case '0': if (i0 === 0) i0 = i; i1 = i; break; default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; } function formatRounded(x: number, p?: number) { const d = formatDecimalParts(x, p); if (!d) { return String(x); } const coefficient = d[0]; const exponent = d[1]; if (exponent < 0) { return '0.' + new Array(-exponent).join('0') + coefficient; } else { if (coefficient.length > exponent + 1) { return coefficient.slice(0, exponent + 1) + '.' + coefficient.slice(exponent + 1); } else { return coefficient + new Array(exponent - coefficient.length + 2).join('0'); } } } // Computes the decimal coefficient and exponent of the specified number x with // significant digits p, where x is positive and p is in [1, 21] or undefined. // For example, formatDecimalParts(1.23) returns ['123', 0]. export function formatDecimalParts(x: number, p?: number): [string, number] | undefined { const sx = p ? x.toExponential(p - 1) : x.toExponential(); const i = sx.indexOf('e'); if (i < 0) { // NaN, ±Infinity return undefined; } const coefficient = sx.slice(0, i); // The string returned by toExponential either has the form \d\.\d+e[-+]\d+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3). return [ coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, +sx.slice(i + 1) ]; } function identity<T>(x: T): T { return x; } export let formatDefaultLocale: FormatLocale; export let format: (specifier: string | FormatSpecifier) => (n: number | { valueOf(): number }) => string; export let formatPrefix: (specifier: string | FormatSpecifier, value: number) => (n: number | { valueOf(): number }) => string; defaultLocale({ thousands: ',', grouping: [3], currency: ['$', ''] }); function defaultLocale(definition: any) { formatDefaultLocale = formatLocale(definition); format = formatDefaultLocale.format; formatPrefix = formatDefaultLocale.formatPrefix; } function exponent(x: number): number { const parts = formatDecimalParts(Math.abs(x)); if (parts) { return parts[1]; } return NaN; } function precisionFixed(step: number) { return Math.max(0, -exponent(Math.abs(step))); } function precisionPrefix(step: number, value: number) { let x = Math.floor(exponent(value) / 3); x = Math.min(8, x); x = Math.max(-8, x); return Math.max(0, x * 3 - exponent(Math.abs(step))); } function precisionRound(step: number, max: number) { step = Math.abs(step); max = Math.abs(max) - step; return Math.max(0, exponent(max) - exponent(step)) + 1; } interface FormatLocaleOptions { /** * The decimal point (e.g., '.') */ decimal: string; /** * The group separator (e.g., ','). Note that the thousands property is a misnomer, * as the grouping definition allows groups other than thousands. */ thousands: string; /** * The array of group sizes (e.g., [3]), cycled as needed. */ grouping: number[]; /** * The currency prefix and suffix (e.g., ['$', '']). */ currency: [string, string]; /** * Array of ten strings to replace the numerals 0-9. */ numerals?: string[]; /** * Symbol to replace the `percent` suffix; the percent suffix (defaults to '%'). */ percent?: string; /** * The minus sign (defaults to '−'). */ minus?: string; /** * The not-a-number value (defaults 'NaN'). */ nan?: string; } export interface FormatLocale { /** * Returns a new format function for the given string specifier. The returned function * takes a number as the only argument, and returns a string representing the formatted number. * * @param specifier A Specifier string. * @throws Error on invalid format specifier. */ format(specifier: string | FormatSpecifier): (n: number | { valueOf(): number }) => string; /** * Returns a new format function for the given string specifier. The returned function * takes a number as the only argument, and returns a string representing the formatted number. * The returned function will convert values to the units of the appropriate SI prefix for the * specified numeric reference value before formatting in fixed point notation. * * @param specifier A Specifier string. * @param value The reference value to determine the appropriate SI prefix. * @throws Error on invalid format specifier. */ formatPrefix(specifier: string | FormatSpecifier, value: number): (n: number | { valueOf(): number }) => string; } export function formatLocale(locale: FormatLocaleOptions): FormatLocale { const group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(Array.prototype.map.call(locale.grouping, Number) as number[], String(locale.thousands)); const currencyPrefix = locale.currency === undefined ? '' : String(locale.currency[0]); const currencySuffix = locale.currency === undefined ? '' : String(locale.currency[1]); const decimal = locale.decimal === undefined ? '.' : String(locale.decimal); const numerals = locale.numerals === undefined ? identity : formatNumerals(Array.prototype.map.call(locale.numerals, String) as string[]); const percent = locale.percent === undefined ? '%' : String(locale.percent); const minus = locale.minus === undefined ? '\u2212' : String(locale.minus); const nan = locale.nan === undefined ? 'NaN' : String(locale.nan); function newFormat(specifier: string | FormatSpecifier): (n: number | { valueOf(): number }) => string { const formatSpecifier = makeFormatSpecifier(specifier); let fill = formatSpecifier.fill; let align = formatSpecifier.align; const sign = formatSpecifier.sign; const symbol = formatSpecifier.symbol; let zero = formatSpecifier.zero; const width = formatSpecifier.width!; let comma = formatSpecifier.comma; let precision = formatSpecifier.precision; let trim = formatSpecifier.trim; let type = formatSpecifier.type; // The 'n' type is an alias for ',g'. if (type as string === 'n') { comma = true; type = 'g'; } else if (!formatTypes[type]) { // The '' type, and any invalid type, is an alias for '.12~g'. if (precision === undefined) { precision = 12; } trim = true; type = 'g'; } // If zero fill is specified, padding goes after sign and before digits. if (zero || (fill === '0' && align === '=')) { zero = true; fill = '0'; align = '='; } // Compute the prefix and suffix. // For SI-prefix, the suffix is lazily computed. const prefix = symbol === '$' ? currencyPrefix : symbol === '#' && /[boxX]/.test(type) ? '0' + type.toLowerCase() : ''; const suffix = symbol === '$' ? currencySuffix : /[%p]/.test(type) ? percent : ''; // What format function should we use? // Is this an integer type? // Can this type generate exponential notation? const formatType = formatTypes[type]; const maybeSuffix = /[defgprs%]/.test(type); // Set the default precision if not specified, // or clamp the specified precision to the supported range. // For significant precision, it must be in [1, 21]. // For fixed precision, it must be in [0, 20]. if (precision === undefined) { precision = 6; } else if (/[gprs]/.test(type)) { precision = Math.max(1, Math.min(21, precision)); } else { precision = Math.max(0, Math.min(20, precision)); } function format(x: number | { valueOf(): number }): string { let valuePrefix = prefix; let valueSuffix = suffix; let value: string; if (type === 'c') { valueSuffix = formatType(+x) + valueSuffix; value = ''; } else { const nx = +x; // Determine the sign. -0 is not less than 0, but 1 / -0 is! var valueNegative = x < 0 || 1 / nx < 0; // Perform the initial formatting. value = isNaN(nx) ? nan : formatType(Math.abs(nx), precision); // Trim insignificant zeros. if (trim) { value = formatTrim(value); } // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign. if (valueNegative && +value === 0 && sign !== '+') { valueNegative = false; } // Compute the prefix and suffix. let signPrefix = valueNegative ? (sign === '(' ? sign : minus) : (sign === '-' || sign === '(' ? '' : sign); let signSuffix = valueNegative && sign === '(' ? ')' : ''; valuePrefix = signPrefix + valuePrefix; valueSuffix = (type === 's' ? prefixes[8 + prefixExponent / 3] : '') + valueSuffix + signSuffix; // Break the formatted value into the integer “value” part that can be // grouped, and fractional or exponential “suffix” part that is not. if (maybeSuffix) { for (let i = 0, n = value.length; i < n; i++) { const c = value.charCodeAt(i); if (48 > c || c > 57) { valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; value = value.slice(0, i); break; } } } } // If the fill character is not '0', grouping is applied before padding. if (comma && !zero) value = group(value, Infinity); // Compute the padding. let length = valuePrefix.length + value.length + valueSuffix.length; let padding = length < width ? new Array(width - length + 1).join(fill) : ''; // If the fill character is '0', grouping is applied after padding. if (comma && zero) { value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity); padding = ''; } // Reconstruct the final output based on the desired alignment. switch (align) { case '<': value = valuePrefix + value + valueSuffix + padding; break; case '=': value = valuePrefix + padding + value + valueSuffix; break; case '^': value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break; default: value = padding + valuePrefix + value + valueSuffix; break; } const { string } = formatSpecifier; if (string) { return string.replace(interpolateRegEx, () => numerals(value)); } return numerals(value); } return format; } function formatPrefix(specifier: string | FormatSpecifier, value: number): (n: number | { valueOf(): number }) => string { const formatSpecifier = makeFormatSpecifier(specifier); formatSpecifier.type = 'f'; const f = newFormat(formatSpecifier); const e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3; const k = Math.pow(10, -e); const prefix = prefixes[8 + e / 3]; return function (value: number | { valueOf(): number }) { return f(k * +value) + prefix; }; } return { format: newFormat, formatPrefix: formatPrefix }; }
the_stack
import _ObnizBLE from './libs/embeds/bleHci/ble'; import _BleAdvertisement from './libs/embeds/bleHci/bleAdvertisement'; import _BleAdvertisementBuilder from './libs/embeds/bleHci/bleAdvertisementBuilder'; import _BleCharacteristic from './libs/embeds/bleHci/bleCharacteristic'; import _BlePeripheral from './libs/embeds/bleHci/blePeripheral'; import { BleConnectionUpdateParam as _BleConnectionUpdateParam } from './libs/embeds/bleHci/blePeripheral'; import { BleConnectionState as _BleConnectionState } from './libs/embeds/bleHci/blePeripheral'; import _BleRemoteCharacteristic from './libs/embeds/bleHci/bleRemoteCharacteristic'; import _BleRemoteDescriptor from './libs/embeds/bleHci/bleRemoteDescriptor'; import _BleRemotePeripheral from './libs/embeds/bleHci/bleRemotePeripheral'; import { BleConnectSetting as _BleConnectSetting } from './libs/embeds/bleHci/bleRemotePeripheral'; import { BlePairingOptions as _BlePairingOptions } from './libs/embeds/bleHci/bleRemotePeripheral'; import { IBeacon as _IBeacon } from './libs/embeds/bleHci/bleRemotePeripheral'; import _BleRemoteService from './libs/embeds/bleHci/bleRemoteService'; import _BleScan from './libs/embeds/bleHci/bleScan'; import { BleScanAdvertisementFilterParam as _BleScanAdvertisementFilterParam } from './libs/embeds/bleHci/bleScan'; import { BleScanSetting as _BleScanSetting } from './libs/embeds/bleHci/bleScan'; import { BleScanTarget as _BleScanTarget } from './libs/embeds/bleHci/bleScan'; import { BleBinary as _BleBinary } from './libs/embeds/bleHci/bleScan'; import { BleScanMode as _BleScanMode } from './libs/embeds/bleHci/bleScan'; import _BleService from './libs/embeds/bleHci/bleService'; import { BleAdvertisementData as _BleAdvertisementData } from './libs/embeds/bleHci/bleTypes'; import { BleCharacteristicDefine as _BleCharacteristicDefine } from './libs/embeds/bleHci/bleTypes'; import { BleDescriptorDefine as _BleDescriptorDefine } from './libs/embeds/bleHci/bleTypes'; import { BlePeripheralDefine as _BlePeripheralDefine } from './libs/embeds/bleHci/bleTypes'; import { BleScanResponseData as _BleScanResponseData } from './libs/embeds/bleHci/bleTypes'; import { BleServiceDefine as _BleServiceDefine } from './libs/embeds/bleHci/bleTypes'; import { BleAdvertisementFlag as _BleAdvertisementFlag } from './libs/embeds/bleHci/bleTypes'; import { BleAttributePropery as _BleAttributePropery } from './libs/embeds/bleHci/bleTypes'; import { BleDeviceAddress as _BleDeviceAddress } from './libs/embeds/bleHci/bleTypes'; import { BleDeviceAddressType as _BleDeviceAddressType } from './libs/embeds/bleHci/bleTypes'; import { BleDeviceType as _BleDeviceType } from './libs/embeds/bleHci/bleTypes'; import { BleEventType as _BleEventType } from './libs/embeds/bleHci/bleTypes'; import { Handle as _Handle } from './libs/embeds/bleHci/bleTypes'; import { UUID as _UUID } from './libs/embeds/bleHci/bleTypes'; import _ObnizBLEHci from './libs/embeds/bleHci/hci'; import _Display from './libs/embeds/display'; import _ObnizSwitch from './libs/embeds/switch'; import { M5StackBasic as _M5StackBasic } from './libs/hw/m5stack_basic'; import { M5StickC as _M5StickC } from './libs/hw/m5stickc'; import _ObnizBoard from './libs/hw/obnizBoard'; import _PeripheralAD from './libs/io_peripherals/ad'; import { AnimationStatus as _AnimationStatus } from './libs/io_peripherals/common'; import { BitType as _BitType } from './libs/io_peripherals/common'; import { DriveType as _DriveType } from './libs/io_peripherals/common'; import { FlowControlType as _FlowControlType } from './libs/io_peripherals/common'; import { ParityType as _ParityType } from './libs/io_peripherals/common'; import { PullType as _PullType } from './libs/io_peripherals/common'; import { StopBitType as _StopBitType } from './libs/io_peripherals/common'; import _Directive from './libs/io_peripherals/directive'; import { DirectiveAnimationFrame as _DirectiveAnimationFrame } from './libs/io_peripherals/directive'; import _PeripheralGrove from './libs/io_peripherals/grove'; import { PeripheralGroveParams as _PeripheralGroveParams } from './libs/io_peripherals/grove'; import { GrovePinOption as _GrovePinOption } from './libs/io_peripherals/grove'; import { PeripheralGroveType as _PeripheralGroveType } from './libs/io_peripherals/grove'; import _PeripheralI2C from './libs/io_peripherals/i2c'; import _PeripheralIO from './libs/io_peripherals/io'; import _PeripheralPWM from './libs/io_peripherals/pwm'; import { PWMInterface as _PWMInterface } from './libs/io_peripherals/pwm'; import { PWMModulateType as _PWMModulateType } from './libs/io_peripherals/pwm'; import _PeripheralSPI from './libs/io_peripherals/spi'; import _PeripheralUART from './libs/io_peripherals/uart'; import { PeripheralUARTOptions as _PeripheralUARTOptions } from './libs/io_peripherals/uart'; import _LogicAnalyzer from './libs/measurements/logicanalyzer'; import { LogicAnalyzerOptions as _LogicAnalyzerOptions } from './libs/measurements/logicanalyzer'; import { LogicAnalyzerOptionsExt as _LogicAnalyzerOptionsExt } from './libs/measurements/logicanalyzer'; import _ObnizMeasure from './libs/measurements/measure'; import { ObnizMeasureOptions as _ObnizMeasureOptions } from './libs/measurements/measure'; import { ObnizMeasureResult as _ObnizMeasureResult } from './libs/measurements/measure'; import _WiFi from './libs/network/wifi'; import _Plugin from './libs/plugin/plugin'; import _Tcp from './libs/protocol/tcp'; import _ObnizUtil from './libs/utils/util'; import _ObnizApi from './ObnizApi'; import _ObnizApp from './ObnizApp'; import ObnizDevice from './ObnizDevice'; import { ObnizBleAttError as _ObnizBleAttError } from './ObnizError'; import { ObnizBleHciStateError as _ObnizBleHciStateError } from './ObnizError'; import { ObnizBleOpError as _ObnizBleOpError } from './ObnizError'; import { ObnizBlePairingRejectByRemoteError as _ObnizBlePairingRejectByRemoteError } from './ObnizError'; import { ObnizBleScanStartError as _ObnizBleScanStartError } from './ObnizError'; import { ObnizBleUnknownCharacteristicError as _ObnizBleUnknownCharacteristicError } from './ObnizError'; import { ObnizBleUnknownDescriptorError as _ObnizBleUnknownDescriptorError } from './ObnizError'; import { ObnizBleUnknownPeripheralError as _ObnizBleUnknownPeripheralError } from './ObnizError'; import { ObnizBleUnknownServiceError as _ObnizBleUnknownServiceError } from './ObnizError'; import { ObnizBleUnsupportedHciError as _ObnizBleUnsupportedHciError } from './ObnizError'; import { ObnizBleUnSupportedOSVersionError as _ObnizBleUnSupportedOSVersionError } from './ObnizError'; import { ObnizDeprecatedFunctionError as _ObnizDeprecatedFunctionError } from './ObnizError'; import { ObnizError as _ObnizError } from './ObnizError'; import { ObnizI2cError as _ObnizI2cError } from './ObnizError'; import { ObnizI2cWarning as _ObnizI2cWarning } from './ObnizError'; import { ObnizOfflineError as _ObnizOfflineError } from './ObnizError'; import { ObnizParameterError as _ObnizParameterError } from './ObnizError'; import { ObnizTimeoutError as _ObnizTimeoutError } from './ObnizError'; import _ObnizPartsInterface from './ObnizPartsInterface'; import { ObnizPartsInfo as _ObnizPartsInfo } from './ObnizPartsInterface'; import { PartsList } from './ObnizPartsList'; /** * obniz class is the abstract version of obniz Board hardware within JavaScript. * * By providing obniz id and instantiating it, you can control obniz Board and the connected parts * without the details of websocket api. * * * ### obnizOS version and obniz.js version * * obniz cloud compare your obniz.js version and target device obnizOS version. * If your js sdk major number is below from OS version (eg obniz.js is 2.0.0 and obnizOS is 3.0.0) then obniz cloud will alert when connection established. * It will work somehow but some functions looses compatibility. * * ### one device from two program * * obniz cloud accept multiple websocket connection from multiple obniz.js at same time. * every commands from obniz.js will passed to a device and every command from a device will be dispatched to every obniz.js connected to the cloud. * * But If one of obniz.js established a connection to a device, then target device will send datas only via local connect. So other connected obniz.js only can send datas and never receive datas from a device. * * If you'd like to receive, you need to specify `local_connect: false` at all of obniz.js to disable local connect. * */ export class Obniz extends ObnizDevice { /** * M5StickC device */ public static M5StickC = _M5StickC; public static M5StackBasic = _M5StackBasic; /** * obniz REST api class * * @returns {ObnizApi} */ public static get api() { return _ObnizApi; } /** * App Support class * * @returns {ObnizApp} */ public static get App() { return _ObnizApp; } } /** * types */ // eslint-disable-next-line no-redeclare // eslint-disable-next-line @typescript-eslint/no-namespace export namespace Obniz { export type ObnizApp = _ObnizApp; export type ObnizApi = _ObnizApi; export type ObnizPartsInfo = _ObnizPartsInfo; export type ObnizPartsInterface = _ObnizPartsInterface; export type BleAdvertisement = _BleAdvertisement; export type BleAdvertisementBuilder = _BleAdvertisementBuilder; export type BleAdvertisementData = _BleAdvertisementData; export type BleCharacteristic = _BleCharacteristic; export type BleCharacteristicDefine = _BleCharacteristicDefine; export type BleConnectionUpdateParam = _BleConnectionUpdateParam; export type BleConnectSetting = _BleConnectSetting; export type BleDescriptorDefine = _BleDescriptorDefine; export type BlePairingOptions = _BlePairingOptions; export type BlePeripheral = _BlePeripheral; export type BlePeripheralDefine = _BlePeripheralDefine; export type BleRemoteCharacteristic = _BleRemoteCharacteristic; export type BleRemoteDescriptor = _BleRemoteDescriptor; export type BleRemotePeripheral = _BleRemotePeripheral; export type BleRemoteService = _BleRemoteService; export type BleScan = _BleScan; export type BleScanAdvertisementFilterParam = _BleScanAdvertisementFilterParam; export type BleScanResponseData = _BleScanResponseData; export type BleScanSetting = _BleScanSetting; export type BleScanTarget = _BleScanTarget; export type BleService = _BleService; export type BleServiceDefine = _BleServiceDefine; export type Directive = _Directive; export type DirectiveAnimationFrame = _DirectiveAnimationFrame; export type Display = _Display; export type IBeacon = _IBeacon; export type LogicAnalyzer = _LogicAnalyzer; export type LogicAnalyzerOptions = _LogicAnalyzerOptions; export type LogicAnalyzerOptionsExt = _LogicAnalyzerOptionsExt; export type M5StackBasic = _M5StackBasic; export type M5StickC = _M5StickC; export type ObnizBLE = _ObnizBLE; export type ObnizBleAttError = _ObnizBleAttError; export type ObnizBLEHci = _ObnizBLEHci; export type ObnizBleHciStateError = _ObnizBleHciStateError; export type ObnizBleOpError = _ObnizBleOpError; export type ObnizBlePairingRejectByRemoteError = _ObnizBlePairingRejectByRemoteError; export type ObnizBleScanStartError = _ObnizBleScanStartError; export type ObnizBleUnknownCharacteristicError = _ObnizBleUnknownCharacteristicError; export type ObnizBleUnknownDescriptorError = _ObnizBleUnknownDescriptorError; export type ObnizBleUnknownPeripheralError = _ObnizBleUnknownPeripheralError; export type ObnizBleUnknownServiceError = _ObnizBleUnknownServiceError; export type ObnizBleUnsupportedHciError = _ObnizBleUnsupportedHciError; export type ObnizBleUnSupportedOSVersionError = _ObnizBleUnSupportedOSVersionError; export type ObnizBoard = _ObnizBoard; export type ObnizDeprecatedFunctionError = _ObnizDeprecatedFunctionError; export type ObnizError = _ObnizError; export type ObnizI2cError = _ObnizI2cError; export type ObnizI2cWarning = _ObnizI2cWarning; export type ObnizMeasure = _ObnizMeasure; export type ObnizMeasureOptions = _ObnizMeasureOptions; export type ObnizMeasureResult = _ObnizMeasureResult; export type ObnizOfflineError = _ObnizOfflineError; export type ObnizParameterError = _ObnizParameterError; export type ObnizSwitch = _ObnizSwitch; export type ObnizTimeoutError = _ObnizTimeoutError; export type ObnizUtil = _ObnizUtil; export type PeripheralAD = _PeripheralAD; export type PeripheralGrove = _PeripheralGrove; export type PeripheralGroveParams = _PeripheralGroveParams; export type PeripheralI2C = _PeripheralI2C; export type PeripheralIO = _PeripheralIO; export type PeripheralPWM = _PeripheralPWM; export type PeripheralSPI = _PeripheralSPI; export type PeripheralUART = _PeripheralUART; export type PeripheralUARTOptions = _PeripheralUARTOptions; export type Plugin = _Plugin; export type PWMInterface = _PWMInterface; export type Tcp = _Tcp; export type WiFi = _WiFi; export type AnimationStatus = _AnimationStatus; export type BitType = _BitType; export type BleAdvertisementFlag = _BleAdvertisementFlag; export type BleAttributePropery = _BleAttributePropery; export type BleBinary = _BleBinary; export type BleConnectionState = _BleConnectionState; export type BleDeviceAddress = _BleDeviceAddress; export type BleDeviceAddressType = _BleDeviceAddressType; export type BleDeviceType = _BleDeviceType; export type BleEventType = _BleEventType; export type BleScanMode = _BleScanMode; export type DriveType = _DriveType; export type FlowControlType = _FlowControlType; export type GrovePinOption = _GrovePinOption; export type Handle = _Handle; export type ParityType = _ParityType; export type PeripheralGroveType = _PeripheralGroveType; export type PullType = _PullType; export type PWMModulateType = _PWMModulateType; export type StopBitType = _StopBitType; export type UUID = _UUID; export type Parts<K extends keyof PartsList> = PartsList[K]['class']; export type PartsOptions<K extends keyof PartsList> = PartsList[K]['options']; }
the_stack
import { EventHandler } from '../render/eventhandler'; export class Vec4 extends EventHandler { isVec4: boolean = true; constructor(private _x: number = 0, private _y: number = 0, private _z: number = 0, private _w: number = 1) { super(); } get x() { return this._x; } set x(value) { if (this._x !== value) { this._x = value; this.fire('change', 'x', this._x, value) } } get y() { return this._y; } set y(value) { if (this._y !== value) { this._y = value; this.fire('change', 'y', this._y, value) } } get z() { return this._z; } set z(value) { if (this._z !== value) { this._z = value; this.fire('change', 'z', this._z, value) } } get w() { return this._w; } set w(value) { if (this._w !== value) { this._w = value; this.fire('change', 'w', this._w, value) } } static isVec4(v: Vec4) { return !isNaN(v.x) && !isNaN(v.y) && !isNaN(v.z) && !isNaN(v.w); } get width() { return this._z; } set width(value) { this._z = value; } get height() { return this._w; } set height(value) { this._w = value; } set(x: number, y: number, z: number, w: number) { this._x = x; this._y = y; this._z = z; this._w = w; return this; } setScalar(scalar: number) { this._x = scalar; this._y = scalar; this._z = scalar; this._w = scalar; return this; } setX(x: number) { this._x = x; return this; } setY(y: number) { this._y = y; return this; } setZ(z: number) { this._z = z; return this; } setW(w: number) { this._w = w; return this; } setComponent(index: number, value: number) { switch (index) { case 0: this._x = value; break; case 1: this._y = value; break; case 2: this._z = value; break; case 3: this._w = value; break; default: throw new Error("index is out of range: " + index); } return this; } getComponent(index: number) { switch (index) { case 0: return this._x; case 1: return this._y; case 2: return this._z; case 3: return this._w; default: throw new Error("index is out of range: " + index); } } clone() { return new Vec4(this._x, this._y, this._z, this._w); } copy(v: { x: number; y: number; z: number; w: number | undefined; }) { this._x = v.x; this._y = v.y; this._z = v.z; this._w = v.w !== undefined ? v.w : 1; return this; } add(v: Vec4, w?: Vec4): Vec4 { if (w !== undefined) { console.warn( "Vec4: .add() now only accepts one argument. Use .addVecs( a, b ) instead." ); return this.addVecs(v, w); } this._x += v.x; this._y += v.y; this._z += v.z; this._w += v.w; return this; } addScalar(s: number) { this._x += s; this._y += s; this._z += s; this._w += s; return this; } addVecs(a: Vec4, b: Vec4) { this._x = a.x + b.x; this._y = a.y + b.y; this._z = a.z + b.z; this._w = a.w + b.w; return this; } addScaledVec(v: Vec4, s: number) { this._x += v.x * s; this._y += v.y * s; this._z += v.z * s; this._w += v.w * s; return this; } sub(v: Vec4, w?: Vec4) { if (w !== undefined) { return this.subVecs(v, w); } this._x -= v.x; this._y -= v.y; this._z -= v.z; this._w -= v.w; return this; } subScalar(s: number) { this._x -= s; this._y -= s; this._z -= s; this._w -= s; return this; } subVecs(a: Vec4, b: Vec4) { this._x = a.x - b.x; this._y = a.y - b.y; this._z = a.z - b.z; this._w = a.w - b.w; return this; } multiplyScalar(scalar: number) { this._x *= scalar; this._y *= scalar; this._z *= scalar; this._w *= scalar; return this; } applyMat4(m: { elements: any; }) { var x = this._x, y = this._y, z = this._z, w = this._w; var e = m.elements; this._x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; this._y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; this._z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; this._w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; return this; } divideScalar(scalar: number) { return this.multiplyScalar(1 / scalar); } setAxisAngleFromQuat(q: { w: number; x: number; y: number; z: number; }) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/QuatToAngle/index.htm // q is assumed to be normalized this._w = 2 * Math.acos(q.w); var s = Math.sqrt(1 - q.w * q.w); if (s < 0.0001) { this._x = 1; this._y = 0; this._z = 0; } else { this._x = q.x / s; this._y = q.y / s; this._z = q.z / s; } return this; } setAxisAngleFromRotationMat(m: { elements: any; }) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var angle, x, y, z, // variables for result epsilon = 0.01, // margin to allow for rounding errors epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; if ( Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon ) { // singularity found // first check for identity matrix which must have +1 for all terms // in leading diagonal and zero in other terms if ( Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2 ) { // this singularity is identity matrix so angle = 0 this.set(1, 0, 0, 0); return this; // zero angle, arbitrary axis } // otherwise this singularity is angle = 180 angle = Math.PI; var xx = (m11 + 1) / 2; var yy = (m22 + 1) / 2; var zz = (m33 + 1) / 2; var xy = (m12 + m21) / 4; var xz = (m13 + m31) / 4; var yz = (m23 + m32) / 4; if (xx > yy && xx > zz) { // m11 is the largest diagonal term if (xx < epsilon) { x = 0; y = 0.707106781; z = 0.707106781; } else { x = Math.sqrt(xx); y = xy / x; z = xz / x; } } else if (yy > zz) { // m22 is the largest diagonal term if (yy < epsilon) { x = 0.707106781; y = 0; z = 0.707106781; } else { y = Math.sqrt(yy); x = xy / y; z = yz / y; } } else { // m33 is the largest diagonal term so base result on this if (zz < epsilon) { x = 0.707106781; y = 0.707106781; z = 0; } else { z = Math.sqrt(zz); x = xz / z; y = yz / z; } } this.set(x, y, z, angle); return this; // return 180 deg rotation } // as we have reached here there are no singularities so we can handle normally var s = Math.sqrt( (m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12) ); // used to normalize if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be // caught by singularity test above, but I've left it in just in case this._x = (m32 - m23) / s; this._y = (m13 - m31) / s; this._z = (m21 - m12) / s; this._w = Math.acos((m11 + m22 + m33 - 1) / 2); return this; } min(v: Vec4) { this._x = Math.min(this._x, v.x); this._y = Math.min(this._y, v.y); this._z = Math.min(this._z, v.z); this._w = Math.min(this._w, v.w); return this; } max(v: Vec4) { this._x = Math.max(this._x, v.x); this._y = Math.max(this._y, v.y); this._z = Math.max(this._z, v.z); this._w = Math.max(this._w, v.w); return this; } clamp(min: Vec4, max: Vec4) { // assumes min < max, componentwise this._x = Math.max(min.x, Math.min(max.x, this._x)); this._y = Math.max(min.y, Math.min(max.y, this._y)); this._z = Math.max(min.z, Math.min(max.z, this._z)); this._w = Math.max(min.w, Math.min(max.w, this._w)); return this; } clampScalar(minVal: number, maxVal: number) { this._x = Math.max(minVal, Math.min(maxVal, this._x)); this._y = Math.max(minVal, Math.min(maxVal, this._y)); this._z = Math.max(minVal, Math.min(maxVal, this._z)); this._w = Math.max(minVal, Math.min(maxVal, this._w)); return this; } clampLength(min: number, max: number) { var length = this.length(); return this.divideScalar(length || 1).multiplyScalar( Math.max(min, Math.min(max, length)) ); } floor() { this._x = Math.floor(this._x); this._y = Math.floor(this._y); this._z = Math.floor(this._z); this._w = Math.floor(this._w); return this; } ceil() { this._x = Math.ceil(this._x); this._y = Math.ceil(this._y); this._z = Math.ceil(this._z); this._w = Math.ceil(this._w); return this; } round() { this._x = Math.round(this._x); this._y = Math.round(this._y); this._z = Math.round(this._z); this._w = Math.round(this._w); return this; } roundToZero() { this._x = this._x < 0 ? Math.ceil(this._x) : Math.floor(this._x); this._y = this._y < 0 ? Math.ceil(this._y) : Math.floor(this._y); this._z = this._z < 0 ? Math.ceil(this._z) : Math.floor(this._z); this._w = this._w < 0 ? Math.ceil(this._w) : Math.floor(this._w); return this; } negate() { this._x = -this._x; this._y = -this._y; this._z = -this._z; this._w = -this._w; return this; } dot(v: Vec4) { return this._x * v.x + this._y * v.y + this._z * v.z + this._w * v.w; } lengthSq() { return ( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); } length() { return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); } manhattanLength() { return ( Math.abs(this._x) + Math.abs(this._y) + Math.abs(this._z) + Math.abs(this._w) ); } normalize() { return this.divideScalar(this.length() || 1); } setLength(length: any) { return this.normalize().multiplyScalar(length); } lerp(v: Vec4, alpha: number) { this._x += (v.x - this._x) * alpha; this._y += (v.y - this._y) * alpha; this._z += (v.z - this._z) * alpha; this._w += (v.w - this._w) * alpha; return this; } lerpVecs(v1: Vec4, v2: any, alpha: any) { return this.subVecs(v2, v1) .multiplyScalar(alpha) .add(v1); } equals(v: Vec4) { return v.x === this._x && v.y === this._y && v.z === this._z && v.w === this._w; } fromArray(array: number[], offset: number = 0) { this._x = array[offset]; this._y = array[offset + 1]; this._z = array[offset + 2]; this._w = array[offset + 3]; return this; } toArray(array: number[] = [], offset: number = 0) { array[offset] = this._x; array[offset + 1] = this._y; array[offset + 2] = this._z; array[offset + 3] = this._w; return array; } fromBufferAttribute(attribute: any, index: any, offset: undefined) { if (offset !== undefined) { console.warn( "Vec4: offset has been removed from .fromBufferAttribute()." ); } this._x = attribute.getX(index); this._y = attribute.getY(index); this._z = attribute.getZ(index); this._w = attribute.getW(index); return this; } } export function v4(x?: number, y?: number, z?: number, w?: number) { return new Vec4(x, y, z, w); }
the_stack
namespace egret.sys { /** * @private * 路径类型 */ export const enum PathType { /** * 纯色填充路径 */ Fill = 1, /** * 渐变填充路径 */ GradientFill, /** * 线条路径 */ Stroke } /** * @private * 2D路径命令 */ export const enum PathCommand { MoveTo = 1, LineTo, CurveTo, CubicCurveTo } /** * @private * 2D路径 */ export class Path2D { /** * 路径类型 */ public type: number = 0; $commands: number[] = []; $data: number | number[][] = []; protected commandPosition: number = 0; protected dataPosition: number = 0; /** * 当前移动到的坐标X * 注意:目前只有drawArc之前会被赋值 */ public $lastX:number = 0; /** * 当前移动到的坐标Y * 注意:目前只有drawArc之前会被赋值 */ public $lastY:number = 0; /** * 将当前绘图位置移动到 (x, y)。如果缺少任何一个参数,则此方法将失败,并且当前绘图位置不改变。 * @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。 * @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。 */ public moveTo(x: number, y: number) { this.$commands[this.commandPosition++] = PathCommand.MoveTo; let pos = this.dataPosition; this.$data[pos++] = x; this.$data[pos++] = y; this.dataPosition = pos; } /** * 使用当前线条样式绘制一条从当前绘图位置开始到 (x, y) 结束的直线;当前绘图位置随后会设置为 (x, y)。 * @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。 * @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。 */ public lineTo(x: number, y: number) { this.$commands[this.commandPosition++] = PathCommand.LineTo; let pos = this.dataPosition; this.$data[pos++] = x; this.$data[pos++] = y; this.dataPosition = pos; } /** * 使用当前线条样式和由 (controlX, controlY) 指定的控制点绘制一条从当前绘图位置开始到 (anchorX, anchorY) 结束的二次贝塞尔曲线。当前绘图位置随后设置为 (anchorX, anchorY)。 * 如果在调用 moveTo() 方法之前调用了 curveTo() 方法,则当前绘图位置的默认值为 (0, 0)。如果缺少任何一个参数,则此方法将失败,并且当前绘图位置不改变。 * 绘制的曲线是二次贝塞尔曲线。二次贝塞尔曲线包含两个锚点和一个控制点。该曲线内插这两个锚点,并向控制点弯曲。 * @param controlX 一个数字,指定控制点相对于父显示对象注册点的水平位置。 * @param controlY 一个数字,指定控制点相对于父显示对象注册点的垂直位置。 * @param anchorX 一个数字,指定下一个锚点相对于父显示对象注册点的水平位置。 * @param anchorY 一个数字,指定下一个锚点相对于父显示对象注册点的垂直位置。 */ public curveTo(controlX: number, controlY: number, anchorX: number, anchorY: number) { this.$commands[this.commandPosition++] = PathCommand.CurveTo; let pos = this.dataPosition; this.$data[pos++] = controlX; this.$data[pos++] = controlY; this.$data[pos++] = anchorX; this.$data[pos++] = anchorY; this.dataPosition = pos; } /** * 从当前绘图位置到指定的锚点绘制一条三次贝塞尔曲线。三次贝塞尔曲线由两个锚点和两个控制点组成。该曲线内插这两个锚点,并向两个控制点弯曲。 * @param controlX1 指定首个控制点相对于父显示对象的注册点的水平位置。 * @param controlY1 指定首个控制点相对于父显示对象的注册点的垂直位置。 * @param controlX2 指定第二个控制点相对于父显示对象的注册点的水平位置。 * @param controlY2 指定第二个控制点相对于父显示对象的注册点的垂直位置。 * @param anchorX 指定锚点相对于父显示对象的注册点的水平位置。 * @param anchorY 指定锚点相对于父显示对象的注册点的垂直位置。 */ public cubicCurveTo(controlX1: number, controlY1: number, controlX2: number, controlY2: number, anchorX: number, anchorY: number) { this.$commands[this.commandPosition++] = PathCommand.CubicCurveTo; let pos = this.dataPosition; this.$data[pos++] = controlX1; this.$data[pos++] = controlY1; this.$data[pos++] = controlX2; this.$data[pos++] = controlY2; this.$data[pos++] = anchorX; this.$data[pos++] = anchorY; this.dataPosition = pos; } /** * 绘制一个矩形 * @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。 * @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。 * @param width 矩形的宽度(以像素为单位)。 * @param height 矩形的高度(以像素为单位)。 */ public drawRect(x: number, y: number, width: number, height: number) { let x2 = x + width; let y2 = y + height; this.moveTo(x, y); this.lineTo(x2, y); this.lineTo(x2, y2); this.lineTo(x, y2); this.lineTo(x, y); } /** * 绘制一个圆角矩形。 * @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。 * @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。 * @param width 矩形的宽度(以像素为单位)。 * @param height 矩形的高度(以像素为单位)。 * @param ellipseWidth 用于绘制圆角的椭圆的宽度(以像素为单位)。 * @param ellipseHeight 用于绘制圆角的椭圆的高度(以像素为单位)。 (可选)如果未指定值,则默认值与为 ellipseWidth 参数提供的值相匹配。 */ public drawRoundRect(x: number, y: number, width: number, height: number, ellipseWidth: number, ellipseHeight?: number): void { let radiusX = (ellipseWidth * 0.5) | 0; let radiusY = ellipseHeight ? (ellipseHeight * 0.5) | 0 : radiusX; if (!radiusX || !radiusY) { this.drawRect(x, y, width, height); return; } let hw = width * 0.5; let hh = height * 0.5; if (radiusX > hw) { radiusX = hw; } if (radiusY > hh) { radiusY = hh; } if (hw === radiusX && hh === radiusY) { if (radiusX === radiusY) { this.drawCircle(x + radiusX, y + radiusY, radiusX); } else { this.drawEllipse(x, y, radiusX * 2, radiusY * 2); } return; } // A-----B // H C // G D // F-----E // 从D点开始,结束在D点 let right = x + width; let bottom = y + height; let xlw = x + radiusX; let xrw = right - radiusX; let ytw = y + radiusY; let ybw = bottom - radiusY; this.moveTo(right, ybw); this.curveTo(right, bottom, xrw, bottom); this.lineTo(xlw, bottom); this.curveTo(x, bottom, x, ybw); this.lineTo(x, ytw); this.curveTo(x, y, xlw, y); this.lineTo(xrw, y); this.curveTo(right, y, right, ytw); this.lineTo(right, ybw); } /** * 绘制一个圆。 * @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。 * @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。 * @param radius 圆的半径(以像素为单位)。 */ public drawCircle(x: number, y: number, radius: number): void { this.arcToBezier(x, y, radius, radius, 0, Math.PI * 2); } /** * 绘制一个椭圆。 * @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。 * @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。 * @param width 矩形的宽度(以像素为单位)。 * @param height 矩形的高度(以像素为单位)。 */ public drawEllipse(x: number, y: number, width: number, height: number): void { let radiusX = width * 0.5; let radiusY = height * 0.5; // 移动x和y到椭圆的中心. x += radiusX; y += radiusY; this.arcToBezier(x, y, radiusX, radiusY, 0, Math.PI * 2); } /** * 绘制一段圆弧路径。圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。 * @param x 圆弧中心(圆心)的 x 轴坐标。 * @param y 圆弧中心(圆心)的 y 轴坐标。 * @param radius 圆弧的半径。 * @param startAngle 圆弧的起始点, x轴方向开始计算,单位以弧度表示。 * 注意,必须在0~2π之间。 * @param endAngle 圆弧的终点, 单位以弧度表示。 * 注意,必须在0~2π之间。 * @param anticlockwise 如果为 true,逆时针绘制圆弧,反之,顺时针绘制。 */ public drawArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean) { if (anticlockwise) { if (endAngle >= startAngle) { endAngle -= Math.PI * 2; } } else { if (endAngle <= startAngle) { endAngle += Math.PI * 2; } } this.arcToBezier(x, y, radius, radius, startAngle, endAngle, anticlockwise); } /** * 绘制一段圆弧路径 * @param x 圆弧中心(圆心)的 x 轴坐标。 * @param y 圆弧中心(圆心)的 y 轴坐标。 * @param radiusX 圆弧的半径 x。 * @param radiusY 圆弧的半径 y。 * @param startAngle 圆弧的起始点, x轴方向开始计算,单位以弧度表示。 * 注意:必须为正数。 * @param endAngle 圆弧的终点, 单位以弧度表示。 * 注意:与startAngle差值必须在0~2π之间。 * @param anticlockwise 如果为 true,逆时针绘制圆弧,反之,顺时针绘制。 * 注意:如果为true,endAngle必须小于startAngle,反之必须大于。 */ private arcToBezier(x: number, y: number, radiusX: number, radiusY: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void { let halfPI = Math.PI * 0.5; let start = startAngle; let end = start; if (anticlockwise) { end += -halfPI - (start % halfPI); if (end < endAngle) { end = endAngle; } } else { end += halfPI - (start % halfPI); if (end > endAngle) { end = endAngle; } } let currentX = x + Math.cos(start) * radiusX; let currentY = y + Math.sin(start) * radiusY; if(this.$lastX != currentX || this.$lastY != currentY) { this.moveTo(currentX, currentY); } let u = Math.cos(start); let v = Math.sin(start); for (let i = 0; i < 4; i++) { let addAngle = end - start; let a = 4 * Math.tan(addAngle / 4) / 3; let x1 = currentX - v * a * radiusX; let y1 = currentY + u * a * radiusY; u = Math.cos(end); v = Math.sin(end); currentX = x + u * radiusX; currentY = y + v * radiusY; let x2 = currentX + v * a * radiusX; let y2 = currentY - u * a * radiusY; this.cubicCurveTo(x1, y1, x2, y2, currentX, currentY); if (end === endAngle) { break; } start = end; if (anticlockwise) { end = start - halfPI; if (end < endAngle) { end = endAngle; } } else { end = start + halfPI; if (end > endAngle) { end = endAngle; } } } } } }
the_stack
import tosource from "https://cdn.skypack.dev/tosource"; import { parse } from "https://deno.land/std@0.97.0/flags/mod.ts"; import { blue, green, red, yellow, } from "https://deno.land/std@0.97.0/fmt/colors.ts"; import { basename, common, dirname, extname, normalize, posix, relative, resolve, } from "https://deno.land/std@0.97.0/path/mod.ts"; import { existsSync, WalkEntry, walkSync, } from "https://deno.land/std@0.97.0/fs/mod.ts"; import type { IBuildPageOptions, IContextData, ICustomComponent, IHTMLAttr, INode, IStaticFile, } from "./types.ts"; import { BUILD_FLAG, BUILDABLE_STATIC_EXT, COMPONENTS_DIR_ABS, CREATORS_DIR_ABS, CREATORS_DIR_BASE, CWD, CWD_OPTION, DEV_FLAG, DIST_DIR_ABS, DIST_STATIC_BASE, HOST_OPTION, ONLY_CREATORS_OPTION, PORT_OPTION, SERVE_HOST, SERVE_PORT, SITEMAP_OPTION, STATIC_DIR_ABS, TEMP_FILES_PREFIX, TEMPLATES_DIR_ABS, TEMPLATES_DIR_BASE, VERBOSITY, WS_HOT_RELOAD_KEY, WS_PING_KEY, } from "./constants.ts"; import defaultTemplate from "./default/_template.ts"; import defaultCreator from "./default/_creator.ts"; import defaultStaticFile from "./default/_static.ts"; export function isDevelopmentEnv(): boolean { return parse(Deno.args)["_"].includes(DEV_FLAG); } export function isProductionEnv(): boolean { const flags = parse(Deno.args); return flags["_"].includes(BUILD_FLAG) || flags["_"].length === 0; } export function tapLog<T extends Array<any>>(...args: T): T { console.log(...args); return args; } export const log = { info: (message: string) => { VERBOSITY === 1 && console.log(blue("info"), message); }, error: (message: string, throwErr: boolean = false) => { if (throwErr) throw new Error(message); else VERBOSITY === 1 && console.log(red("error"), message); }, warning: (message: string) => { VERBOSITY === 1 && console.log(yellow("warning"), message); }, success: (message: string) => { VERBOSITY === 1 && console.log(green("success"), message); }, }; /** * Get number of seconds between a number (performance.now) and now */ export function getSecondsFrom(t0: number): string { return ((performance.now() - t0) / 1000).toFixed(3); } /** * Check if a file is a script file (JS or TS) */ export function isScript(filename: string): boolean { return filename.endsWith(".ts") || filename.endsWith(".js"); } /** * Check if a file is a template file (HTML or HTM) */ export function isTemplate(filename: string): boolean { return filename.endsWith(".html") || filename.endsWith(".htm"); } /** * Evaluate the given expression in a given context */ export function contextEval( expression: string, context: IContextData, errorContext?: string, ) { try { const richContext = { // adding useful functions to context ssgo: { assrc: (expression: any) => tosource(expression).replaceAll(/(?<!\\)(?:\\\\)*"/gi, `'`), }, ...context, }; // @ts-ignore for (const key of Object.keys(richContext)) window[key] = richContext[key]; const evaluation = eval(`(${expression})`); // @ts-ignore for (const key of Object.keys(richContext)) delete window[key]; return evaluation; } catch (e) { if (typeof errorContext !== "undefined") { log.error( `When trying to evaluate '${errorContext.trim()}': ${e.message}`, true, ); } } } /** * Get attributes as a name="value" string */ export function formatAttributes(attributes: IHTMLAttr[]): string { let result = ""; for (let attribute of attributes) { result += ` ${attribute.name.value}`; if (typeof attribute.value?.value !== "undefined") { result += `="${attribute.value.value}"`; } } return result.trim(); } /** * Handle interpolation of text with context data */ export function interpolate(templateStr: string, data?: IContextData) { return templateStr.replace(/{{(([^}][^}]?|[^}]}?)*)}}/g, (match) => { // remove "{{" and "}}" const cleanedMatch = match.trim().slice(2, -2).trim(); return contextEval(cleanedMatch, data ?? {}, templateStr); }); } /** * Remove the extension from a file name */ export function removeExt(basename: string) { return basename.split(".").slice(0, -1).join("."); } /** * Tell if node is a comment node */ export function isComment(node: INode): boolean { return "rawName" in node && node.rawName === "!--"; } /** * Remove a node from its parent */ export function removeFromParent(node: INode) { if (!!node.parent) { const parent = "body" in node.parent ? node.parent?.body : node.parent; const index = (parent as Array<INode>).findIndex((n) => n === node); if (index !== -1) (parent as Array<INode>).splice(index, 1); } } /** * Add a item next to another inside of parent */ export function pushBefore<T>(array: T[], before: T, ...items: T[]) { const index = array.findIndex((i) => i === before); array.splice(index, 0, ...items); } /** * Get attribute name without its prefix (eval:, static:) */ export function getUnprefixedAttributeName(attribute: IHTMLAttr) { return attribute.name.value.split(":").slice(1).join(":"); } /** * Get path of dist built page */ export function getOutputPagePath(options: IBuildPageOptions): string { return resolve( CWD, DIST_DIR_ABS, options.dir ?? "", options.filename.endsWith(".html") ? options.filename : options.filename + ".html", ); } /** * Check if a URL leads to an external ressource */ export function isExternalURL(url: string) { return new RegExp("^(?:[a-z]+:)?//", "i").test(url); } export function getStaticFileFromRel(staticRel: string): IStaticFile { const staticFileAbs = normalize(`${STATIC_DIR_ABS}/${staticRel}`); const staticFileBasename = basename(staticFileAbs); return { path: staticFileAbs, isCompiled: BUILDABLE_STATIC_EXT.includes( posix.extname(staticFileBasename), ), }; } /** * Get future path of static file in bundle */ export function getStaticFileBundlePath(staticRel: string): string { const ext = [".jsx", ".tsx", ".ts"].includes(extname(staticRel)) ? ".js" : extname(staticRel); const base = basename(staticRel); const filename = base.startsWith(".") ? staticRel : removeExt(staticRel); return normalize(`/${DIST_STATIC_BASE}/${filename}${ext}`); } /** * Check if a file is inside of a directory */ export function isFileInDir(fileAbs: string, dirAbs: string): boolean { return ( common([fileAbs, dirAbs]) === dirAbs || common([fileAbs, dirAbs]) === dirAbs + "/" ); } /** * Check if a given path is absolute */ export function isPathAbsolute(path: string) { return /^(?:\/|[a-z]+:\/\/)/.test(path); } /** * Get path relative to cwd */ export function getRel(abs: string): string { return relative(CWD, abs); } /** * Copy the content of a file to a temp file and returns the temp path */ export function writeTempFileWithContentOf(contentAbs: string): string { const contentStr = Deno.readTextFileSync(contentAbs); const tempAbs = Deno.makeTempFileSync({ dir: dirname(contentAbs), prefix: TEMP_FILES_PREFIX, suffix: extname(contentAbs), }); Deno.writeTextFileSync(tempAbs, contentStr); return tempAbs; } /** * Dynamically import module from abs path * Using a temp file to hack import cache if in development mode */ export async function importModule(moduleAbs: string) { const isDevEnv = isDevelopmentEnv(); const tempModuleAbs = isDevEnv ? writeTempFileWithContentOf(moduleAbs) : moduleAbs; const module = await import(`file://${tempModuleAbs}`); isDevEnv && Deno.remove(tempModuleAbs); return module; } /** * Clean the temp files left in project */ export function cleanTempFiles() { const tempFiles: WalkEntry[] = Array.from( walkSync(CWD), ).filter((file: WalkEntry) => file.name.startsWith(TEMP_FILES_PREFIX)); for (const file of tempFiles) { Deno.removeSync(file.path, { recursive: true }); } } // ----- errors ----- // /** * Check that a template has at least one node */ export function checkEmptyTemplate( parsedTemplate: INode[], templateAbs: string, ) { if (parsedTemplate.length === 0) { log.warning( `When parsing '${ getRel( templateAbs, ) }': This template/component file is empty.`, ); } } /** * Check if two components have the same name */ export function checkComponentNameUnicity(components: ICustomComponent[]) { for (let component of components) { if ( components.some( (c) => removeExt(c.name) === removeExt(component.name) && c.path !== component.path, ) ) { log.error( `When listing custom components: Two components with the same name '${ removeExt( component.name, ) }' found.`, true, ); } } } /** * Check that buildPage options are valid */ export function checkBuildPageOptions( templateRel: string, options: IBuildPageOptions, ) { if (!options.filename) { log.error( `When building page with template '${templateRel}': No filename given to 'buildPage' call.`, true, ); } } /** * Check that a static file exists and can be included in bundle */ export function checkStaticFileExists( staticFileAbs: string, staticAttrValue: string, ): boolean { if (!existsSync(staticFileAbs)) { log.warning( `Could not resolve ${staticAttrValue}: won't be included in output build.`, ); return false; } return true; } /** * Check if a file is inside static/ dir */ export function checkStaticFileIsInsideStaticDir( staticFileAbs: string, staticAttrValue: string, ) { if (common([staticFileAbs, STATIC_DIR_ABS]) !== STATIC_DIR_ABS) { log.warning( `Could not resolve ${staticAttrValue} inside of 'static/' dir: won't be included in output build.`, ); return false; } return true; } /** * Get the state of a directory * noexists -> directory doesn't exist * exists -> directory exists and isn't empty * empty -> directory exists but is empty */ export function getDirState(abs: string): "exists" | "empty" | "noexists" { return !existsSync(abs) ? "noexists" : Array.from(walkSync(abs)).filter((e) => e.path !== abs).length > 0 ? "exists" : "empty"; } /** * Check that mandatory directories exist */ export function checkProjectDirectoriesExist(throwErr: boolean = false) { const creatorsState = getDirState(CREATORS_DIR_ABS); if (creatorsState === "noexists" && throwErr) { log.error( `Could not find mandatory '${CREATORS_DIR_BASE}/' directory.`, throwErr, ); } const templatesState = getDirState(TEMPLATES_DIR_ABS); if (templatesState === "noexists" && throwErr) { log.error( `Could not find mandatory '${TEMPLATES_DIR_BASE}/' directory.`, throwErr, ); } return { [CREATORS_DIR_ABS]: creatorsState, [TEMPLATES_DIR_ABS]: templatesState, [STATIC_DIR_ABS]: getDirState(STATIC_DIR_ABS), [COMPONENTS_DIR_ABS]: getDirState(COMPONENTS_DIR_ABS), }; } /** * Check if a string is a valid URL starting with http or https */ export function checkIsValidHttpUrl(str: string, throwErr = true) { let url; try { url = new URL(str); if (url.protocol !== "http:" && url.protocol !== "https:") { throw ""; } } catch (_) { const error = `When trying to build sitemap.xml: '${str}' is not a valid URL starting with 'http://' or 'https://'.`; log.error(error, throwErr); return false; } return true; } /** * Check if a string is a valid port number */ export function checkIsValidPortNumber(str: string, throwErr = true) { if (Number.isNaN(Number.parseInt(str, 10))) { const error = `When trying to serve 'dist/': '${str}' is not a valid port number.`; log.error(error, throwErr); return false; } return true; } /** * Check if a string is a valid hostname or IP */ export function checkIsValidHostnameOrIP(str: string, throwErr = true) { if ( !new RegExp( /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/gm, ).test(str) ) { const error = `When trying to serve 'dist/': '${str}' is not a valid host or IP.`; log.error(error, throwErr); return false; } return true; } export function checkIsValidOnlyCreatorsString(str: string, throwErr = true) { if (typeof str !== "string") { const error = `When trying to narrow creators to run: '${str}' is not a valid list of creators (comma separated).`; log.error(error, throwErr); return false; } return true; } export function checkIsValidCWD(str: string, throwErr = true) { if (!existsSync(CWD)) { const error = `Invalid current working directory provided: ${CWD} does not exists.`; log.error(error, throwErr); return false; } return true; } /** * Check if provided CLI flags are valid */ export function checkAreValidCLIOptions(options: Record<string, any>) { const isDevEnv = isDevelopmentEnv(); const isProdEnv = isProductionEnv(); const validators: Record<string, Function> = { [SITEMAP_OPTION]: (value: string) => !isProdEnv || checkIsValidHttpUrl(value, false), [PORT_OPTION]: (value: string) => !isDevEnv || checkIsValidPortNumber(value, false), [HOST_OPTION]: (value: string) => !isDevEnv || checkIsValidHostnameOrIP(value, false), [ONLY_CREATORS_OPTION]: (value: string) => checkIsValidOnlyCreatorsString(value, false), [CWD_OPTION]: (value: string) => checkIsValidCWD(value, false), }; for (let key of Object.keys(options)) { if (key in validators) { !validators[key](options[key]) && Deno.exit(1); } } return options; } /** * Get an error page formatted with the given error */ export function getFormattedErrorPage( errorMessage: string, errorStack?: string, ) { const escapeTags = (str: string) => str.replace("<", "&lt;").replace(">", "&gt;"); return ` <section style="font-family: sans-serif; padding: 1px 10px;"> <h1 style="color: #D2283C;"><code>${escapeTags(errorMessage)}</code></h1> <div style="padding: 10px; background-color: #FDF3F4; border-radius: 1px; width: fit-content;"> <code style="font-weight: bold; font-size: 1.3rem; white-space: pre-wrap;">${ errorStack ? escapeTags(errorStack) : "No error stack provided." }</code> </div> </section> `; } export function createDefaultTemplate() { Deno.writeTextFileSync( resolve(TEMPLATES_DIR_ABS, "index.html"), defaultTemplate, ); } export function createDefaultCreator() { Deno.writeTextFileSync(resolve(CREATORS_DIR_ABS, "index.ts"), defaultCreator); } export function createDefaultStaticFile() { Deno.writeTextFileSync( resolve(STATIC_DIR_ABS, "index.css"), defaultStaticFile, ); } /** * Inject the hot reload serve script inside of the given page */ export function injectServeWebsocketScript(pageContent: string): string { const scriptContent = ` <script> let isFirstConnection = true; function connect() { const ws = new WebSocket('ws://${SERVE_HOST}:${SERVE_PORT}/__ws'); ws.onmessage = ({ data }) => { if (data === '${WS_HOT_RELOAD_KEY}') { location.reload(); } } // retrying to connect when closing ws.onopen = () => { if (!isFirstConnection) location.reload(); else isFirstConnection = false; ws.onclose = () => { setInterval(() => connect(), 10000); } } // maintain connection setInterval(() => { if (ws.readyState === 1) ws.send('${WS_PING_KEY}') }, 10000); } connect(); </script>`; return pageContent + scriptContent; }
the_stack
import * as DiscoveryEntry from "../../generated/joynr/types/DiscoveryEntry"; import * as Typing from "../util/Typing"; /** * Private function. This function returns the hashCode of the given discovery entry, this should uniquely identify a * discovery entry within the capability directory. * * @param discoveryEntry - discovery entry */ function hashCode(discoveryEntry: DiscoveryEntry): string { return ( discoveryEntry.domain + discoveryEntry.interfaceName + discoveryEntry.participantId + discoveryEntry.providerVersion.majorVersion + discoveryEntry.providerVersion.minorVersion + discoveryEntry.publicKeyId ); } /** * Private function. Returns a key for indexing by the domain, interfaceName and providerQos. * * @param domain - the domain * @param interfaceName - the interface name * @returns the unique key for the domain and interface name */ function getDomainInterfaceNameKey(domain: string, interfaceName: string): string { return domain + interfaceName; } class CapabilitiesStore { private registeredCapabilitiesTime: Record<string, number> = {}; // discovery entry hashCode -> Array of Capability Information private discoveryEntryStore: Record<string, any> = {}; // domain + interface -> Array of GlobalDiscoveryEntry private discoveryEntryStoreByDomainInterfaceName: Record<string, any[]> = {}; // participantId -> Array of Capability Information private discoveryEntryStoreByParticipantId: Record<string, any> = {}; /** * The Local Capabilities Storage * * @constructor * * @classdesc * The <code>CapabilitiesStore</code> is a joynr internal interface. When a provider that is registered with joynr, the framework creates an * entry for that provider in the capabilities directory. These <code>{@link DiscoveryEntry}</code> entries contain access * information as well as supported Qos. The information is later used in the arbitration process to pick a provider for a proxy. * * @param initialCapabilities */ public constructor(initialCapabilities?: DiscoveryEntry[]) { if (initialCapabilities && initialCapabilities.length > 0) { this.add({ discoveryEntries: initialCapabilities }); } } /** * Unregisters a discovery entry from the store. * * @param participantId - the participant ID uniquely identifying the discovery entry to be removed */ private removeDiscoveryEntryFromStore(participantId: string): void { const discoveryEntry = this.discoveryEntryStoreByParticipantId[participantId]; // unregister by participant id delete this.discoveryEntryStoreByParticipantId[participantId]; if (discoveryEntry !== undefined) { // unregister by domain and interface const domainInterfaceKey = getDomainInterfaceNameKey(discoveryEntry.domain, discoveryEntry.interfaceName); this.discoveryEntryStoreByDomainInterfaceName[ domainInterfaceKey ] = this.discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey].filter(cap => { if ( cap.interfaceName === discoveryEntry.interfaceName && cap.domain === discoveryEntry.domain && cap.participantId === discoveryEntry.participantId ) { return false; } return true; }); // unregister master store const key = hashCode(discoveryEntry); delete this.discoveryEntryStore[key]; } } /** * Registers discovery entry to the store. * * @param discoveryEntry - the capability to register */ private addDiscoveryEntryToStore(discoveryEntry: DiscoveryEntry): void { let entryFound = false, entryId, entry; const discoveryEntryKey = hashCode(discoveryEntry); // master store, storing key to actual discovery entry object const isAlreadyThere = this.discoveryEntryStore[discoveryEntryKey]; if (isAlreadyThere !== undefined) { this.removeDiscoveryEntryFromStore(isAlreadyThere); } this.discoveryEntryStore[discoveryEntryKey] = discoveryEntry; this.registeredCapabilitiesTime[discoveryEntryKey] = Date.now(); // by participant id this.discoveryEntryStoreByParticipantId[discoveryEntry.participantId] = discoveryEntry; // by domain interface and provider qos const domainInterfaceKey = getDomainInterfaceNameKey(discoveryEntry.domain, discoveryEntry.interfaceName); if (this.discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] === undefined) { this.discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] = []; } const discoveryEntries = this.discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey]; for (entryId in discoveryEntries) { if (discoveryEntries.hasOwnProperty(entryId) && !entryFound) { entry = discoveryEntries[entryId]; if (entry.participantId === discoveryEntry.participantId) { entryFound = true; } } } if (!entryFound) { this.discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey].push(discoveryEntry); } } /** * Registers either a single discovery entry or a list of discovery entry to the store. * * @param settings - an object containing the required parameters * @param settings.discoveryEntries - an array of discovery entries to register * @param settings.discoveryEntry a single discovery entry to register (only if settings.discoveryEntries is not supplied) * @param settings.remote true if the provided entry/entries are gathered from remote * * @returns returns this for a fluent interface */ public add(settings: { discoveryEntries?: DiscoveryEntry[]; discoveryEntry?: DiscoveryEntry; remote?: boolean; }): CapabilitiesStore { if (settings.discoveryEntries !== undefined && Typing.getObjectType(settings.discoveryEntries) === "Array") { for (let i = 0; i < settings.discoveryEntries.length; i++) { this.addDiscoveryEntryToStore(settings.discoveryEntries[i]); } } else if (settings.discoveryEntry !== undefined) { this.addDiscoveryEntryToStore(settings.discoveryEntry); } else { throw new Error( "missing arguments for function CapabilitiesStore.add: neither settings.discoveryEntries nor settings.discoveryEntry are provided" ); } return this; } /** * checks if the provided discoveryEntry is not older than the second argument maxAge * * @param discoveryEntry - the discovery entry to check * @param maxAge - the maximum age of the discovery entry */ private checkAge(discoveryEntry: DiscoveryEntry, maxAge?: number): boolean { const registrationTime = this.registeredCapabilitiesTime[hashCode(discoveryEntry)]; if (registrationTime === undefined || maxAge === undefined) { return true; } return Date.now() - registrationTime <= maxAge; } /** * checks if the discoveryQos matches with the discoveryEntry * * @param discoveryEntry - the discovery entry to check * @param cacheMaxAge - the maximum age of the discovery entry */ private qosMatches(discoveryEntry: DiscoveryEntry, cacheMaxAge?: number): boolean { return discoveryEntry !== undefined && this.checkAge(discoveryEntry, cacheMaxAge); } /** * filters provided entries and returns only local entries * * @param entries - the discovery entries to be filtered * @param cacheMaxAge - the maximum age of the discovery entries */ private filterEntries(entries: DiscoveryEntry[], cacheMaxAge?: number): DiscoveryEntry[] { const returnValue = []; for (let i = entries.length - 1; i >= 0; i--) { const discoveryEntry = entries[i]; if (this.qosMatches(discoveryEntry, cacheMaxAge)) { returnValue.push(discoveryEntry); } } return returnValue; } /** * Looks up a list of capabilities either for a given participant ID or for a given domain / interfaceName combination * * @param settings - an object containing the required parameters * @param settings.domains - the name of the domains * @param settings.interfaceName - the interface name of the capability * @param settings.participantId - the participantId of the capability * @param settings.cacheMaxAge - max age used for filtering the store entries * * @returns a list of matching discovery entries. */ public lookup(settings: { domains: string[]; interfaceName: string; cacheMaxAge?: number }): DiscoveryEntry[]; public lookup(settings: { participantId: string; cacheMaxAge?: number }): DiscoveryEntry[]; public lookup(settings: any): DiscoveryEntry[] { if (settings.domains !== undefined && settings.interfaceName !== undefined) { let returnValue: DiscoveryEntry[] = []; for (let i = 0; i < settings.domains.length; ++i) { const key = getDomainInterfaceNameKey(settings.domains[i], settings.interfaceName); const storedEntries = this.discoveryEntryStoreByDomainInterfaceName[key] || []; returnValue = returnValue.concat(this.filterEntries(storedEntries, settings.cacheMaxAge)); } return returnValue; } else if (settings.participantId !== undefined) { const storedEntries = this.discoveryEntryStoreByParticipantId[settings.participantId]; if (this.qosMatches(storedEntries, settings.cacheMaxAge)) { return [storedEntries]; } else { return []; } } else { throw new Error( "missing arguments for function CapabilitiesStore.lookup: neither settings.domain + settings.interfaceName nor settings.participantId are provided" ); } } /** * Unregisters either a list of discovery entries or a single discovery entry from the store. * * @param settings - an object containing the required parameters * @param settings.participantIds - an array of participant IDs uniquely identifying the discovery entry to be removed * @param settings.participantId - a participant ID uniquely identifying the discovery entry to be removed * * @returns returns this for a fluent interface */ public remove(settings: { participantIds?: string[]; participantId?: string }): CapabilitiesStore { if (settings.participantIds !== undefined && Typing.getObjectType(settings.participantIds) === "Array") { for (let i = 0; i < settings.participantIds.length; i++) { this.removeDiscoveryEntryFromStore(settings.participantIds[i]); } } else if (settings.participantId !== undefined) { this.removeDiscoveryEntryFromStore(settings.participantId); } else { throw new Error( "missing arguments for function CapabilitiesStore.remove: neither settings.participantIds nor settings.participantId are provided" ); } return this; } } export = CapabilitiesStore;
the_stack